Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(quill-charts): make charts easy to test under any wrapper (#123134)

Sam Pennington654405cb1f82
diff --git a/frontend/src/lib/components/Sparkline.test.tsx b/frontend/src/lib/components/Sparkline.test.tsx
index f4b1ec939b0e..fc18ff603931 100644
--- a/frontend/src/lib/components/Sparkline.test.tsx
+++ b/frontend/src/lib/components/Sparkline.test.tsx
@@ -1,32 +1,14 @@
import '@testing-library/jest-dom'
-import { cleanup, render, waitFor } from '@testing-library/react'
+import { render } from '@testing-library/react'
-import {
- createDefaultTooltipAccessor,
- getChart,
- hoverUntilTooltip,
- setupJsdom,
- setupSyncRaf,
-} from '@posthog/quill-charts/testing'
+import { findChart, getChart, setupChartTests } from '@posthog/quill-charts/testing'
import { initKeaTests } from '~/test/init'
import { Sparkline, SparklineProps } from './Sparkline'
-let cleanupJsdom: () => void
-let cleanupRaf: () => void
-
-beforeEach(() => {
- cleanupJsdom = setupJsdom()
- cleanupRaf = setupSyncRaf()
-})
-
-afterEach(() => {
- cleanupRaf()
- cleanupJsdom()
- cleanup()
-})
+setupChartTests()
function renderSparkline(props: SparklineProps): void {
initKeaTests()
@@ -64,11 +46,9 @@ describe('Sparkline', () => {
renderLabel: (label) => `Day: ${label}`,
renderTooltipValue: (value) => `$${value.toFixed(2)}`,
})
- const chart = getChart()
+ const tooltip = await (await findChart()).hoverTooltip(2)
- const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 2, LABELS.length))
- // The portal mounts before its content commits, so poll until the header lands.
- await waitFor(() => expect(tooltip.label()).toBe('Day: Wed'))
+ expect(tooltip.label()).toBe('Day: Wed')
expect(tooltip.value('volume')).toBe('$3.00')
expect(tooltip.rows()).toEqual(['volume'])
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx
index 9cf16dfae891..6361b7736cf4 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx
@@ -146,7 +146,7 @@ describe('SqlBarGraph', () => {
if (dateBucket === 'year') {
expect(getChart().xTicks()).toContain('2025')
} else if (chartType !== ChartDisplayType.ActionsBarValue) {
- expect((await sqlChart.hoverTooltip(HOVER, dates.length)).label()).toBe('Dec 1, 00:00')
+ expect((await sqlChart.hoverTooltip(HOVER)).label()).toBe('Dec 1, 00:00')
}
await clickAtIndex(canvas.parentElement!, HOVER, dates.length)
expect(await screen.findByText('Explore this result')).toBeVisible()
@@ -307,7 +307,7 @@ describe('SqlBarGraph', () => {
)
await screen.findByLabelText(/chart with/i)
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
// formatSqlSeriesValue output — matches the line/combo tooltips, not toLocaleString.
expect(tooltip.value('a')).toBe('3000')
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
index da0aec5e4782..341b105d84da 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
@@ -106,7 +106,7 @@ it.each([
),
})
await screen.findByLabelText(/chart with 2 data series/i)
- await sqlChart.hoverTooltip(1, 3)
+ await sqlChart.hoverTooltip(1)
fireEvent.click(getChart().element)
fireEvent.click(screen.getByText('b', { selector: '[data-attr="hog-chart-tooltip-series"]' }))
expect(onPointClick).toHaveBeenCalledWith('b-1', 1, 'Tue')
@@ -296,7 +296,7 @@ describe('SqlLineGraph', () => {
lineFixture([{ name: 'pageviews', valueAt: (i) => (i + 1) * 100 }])
)
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
expect(tooltip.value('pageviews')).toBe('300')
expect(tooltip.label()).toBe('Dec 1, 2025')
@@ -307,7 +307,7 @@ describe('SqlLineGraph', () => {
renderLine({ yAxis: [{ column: 'a' }, { column: 'b' }] }, twoSeries())
await screen.findByLabelText(/chart with 2 data series/i)
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
expect(tooltip.rows()).toEqual(['a', 'b'])
expect(tooltip.value('a')).toBe('300')
@@ -327,7 +327,7 @@ describe('SqlLineGraph', () => {
lineFixture([{ name: 'a', type: 'Float64', valueAt: (i) => (i === HOVER ? value : value / 2) }])
)
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
// compactNumber separates magnitude with a non-breaking space; normalize for comparison.
expect(tooltip.value('a')?.replace(/\u00a0/g, ' ')).toBe(expected)
@@ -340,7 +340,7 @@ describe('SqlLineGraph', () => {
renderLine({ yAxis: [{ column: 'a' }, { column: 'b' }], showTotalRow }, twoSeries())
await screen.findByLabelText(/chart with 2 data series/i)
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
expect(tooltip.total()).toBe(expectedTotal)
})
@@ -359,7 +359,7 @@ describe('SqlLineGraph', () => {
)
await screen.findByLabelText(/chart with 2 data series/i)
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
expect(tooltip.swatchColors()).toEqual(['rgb(255, 0, 0)', 'rgb(0, 255, 0)'])
})
@@ -407,7 +407,7 @@ describe('SqlLineGraph', () => {
fireEvent.click(bButton, { metaKey: additive })
await waitFor(() => expect(getChart().seriesCount).toBe(1))
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
expect(tooltip.rows()).toEqual(expectedRows)
})
})
@@ -486,7 +486,7 @@ describe('SqlLineGraph', () => {
// One data series + one trend line = 2 rendered series.
await waitFor(() => expect(getChart().seriesCount).toBe(2))
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
expect(tooltip.rows()).toEqual(['a'])
})
})
@@ -535,7 +535,7 @@ describe('SqlLineGraph', () => {
})
await screen.findByLabelText(/chart with 2 data series/i)
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
expect(tooltip.value('a')).toBe('300')
})
})
@@ -554,7 +554,7 @@ describe('SqlLineGraph', () => {
])('$name', async ({ showNullsAsZero, expected }) => {
renderLine({ yAxis: [{ column: 'a' }], showNullsAsZero }, withGap())
- const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)
+ const tooltip = await sqlChart.hoverTooltip(HOVER)
expect(tooltip.value('a')).toBe(expected)
})
})
diff --git a/frontend/src/test/insight-testing/interactions.ts b/frontend/src/test/insight-testing/interactions.ts
index 0f8bd02785b5..b825c6f8a8e4 100644
--- a/frontend/src/test/insight-testing/interactions.ts
+++ b/frontend/src/test/insight-testing/interactions.ts
@@ -2,11 +2,9 @@ import { fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
- clickAtIndex,
- createDefaultTooltipAccessor,
type DefaultTooltipAccessor,
+ findChart,
getChartTooltip,
- hoverUntilTooltip,
waitForChartTooltip,
} from '@posthog/quill-charts/testing'
@@ -19,7 +17,6 @@ import { trendsDataLogic } from 'products/product_analytics/frontend/insights/tr
import { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'
import { INSIGHT_TEST_ID } from './render-insight'
-import { trendsSeries } from './test-data'
import { type InsightTooltipAccessor, createInsightTooltipAccessor } from './tooltip-helpers'
const DEBOUNCE_TIMEOUT = 3000
@@ -34,12 +31,6 @@ const CHART_INTERACTION_TIMEOUT = 4000
/** Milliseconds left until `deadline`, floored so the wait still gets one poll. */
const budgetUntil = (deadline: number): number => Math.max(50, deadline - Date.now())
-/** The chart's event-handling wrapper, once its canvas has rendered. */
-async function findChartWrapper(deadline: number): Promise<HTMLElement> {
- const canvas = await screen.findByLabelText(/chart with/i, {}, { timeout: budgetUntil(deadline) })
- return canvas.parentElement!
-}
-
function getLogic(): ReturnType<typeof insightVizDataLogic.build> {
const props: InsightLogicProps = { dashboardItemId: INSIGHT_TEST_ID }
return insightVizDataLogic(props)
@@ -161,19 +152,16 @@ export function getQuerySource(): TrendsQuery {
export const chart = {
/** Current chart tooltip element, or null if none is rendered. */
getTooltip: getChartTooltip,
- async hoverTooltip(
- index: number,
- totalLabels = trendsSeries.pageviews.labels.length
- ): Promise<InsightTooltipAccessor> {
+ async hoverTooltip(index: number): Promise<InsightTooltipAccessor> {
const deadline = Date.now() + CHART_INTERACTION_TIMEOUT
- const wrapper = await findChartWrapper(deadline)
- const tooltip = await hoverUntilTooltip(wrapper, index, totalLabels, budgetUntil(deadline))
- return createInsightTooltipAccessor(tooltip)
+ const chart = await findChart({ timeout: budgetUntil(deadline) })
+ const tooltip = await chart.hoverTooltip(index, budgetUntil(deadline))
+ return createInsightTooltipAccessor(tooltip.element)
},
- async clickAtIndex(index: number, totalLabels = trendsSeries.pageviews.labels.length): Promise<void> {
+ async clickAtIndex(index: number): Promise<void> {
const deadline = Date.now() + CHART_INTERACTION_TIMEOUT
- const wrapper = await findChartWrapper(deadline)
- await clickAtIndex(wrapper, index, totalLabels, budgetUntil(deadline))
+ const chart = await findChart({ timeout: budgetUntil(deadline) })
+ await chart.clickAtIndex(index, budgetUntil(deadline))
},
/** Click a row inside the pinned tooltip by matching its label text. Use
* after `clickAtIndex` has pinned a multi-series tooltip. */
@@ -189,13 +177,11 @@ export const chart = {
}
/** Interactions for SQL (`DataVisualizationNode`) charts, which render quill's `DefaultTooltip`
- * instead of the InsightTooltip table — so the tooltip is read via quill's `createDefaultTooltipAccessor`.
- * `totalLabels` (the x-axis label count) is required: there's no canonical default series. */
+ * instead of the InsightTooltip table. */
export const sqlChart = {
- async hoverTooltip(index: number, totalLabels: number): Promise<DefaultTooltipAccessor> {
+ async hoverTooltip(index: number): Promise<DefaultTooltipAccessor> {
const deadline = Date.now() + CHART_INTERACTION_TIMEOUT
- const wrapper = await findChartWrapper(deadline)
- const tooltip = await hoverUntilTooltip(wrapper, index, totalLabels, budgetUntil(deadline))
- return createDefaultTooltipAccessor(tooltip)
+ const chart = await findChart({ timeout: budgetUntil(deadline) })
+ return await chart.hoverTooltip(index, budgetUntil(deadline))
},
}
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index b896924db254..7b39fdd7ead2 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -105,7 +105,7 @@ Charts fill their container and need a parent with real dimensions — a zero-he
## Testing
-Import helpers from `@posthog/quill-charts/testing` (jsdom only): `getChart` reads rendered overlays through stable `data-attr` hooks, `renderChart` adds tooltip-context capture for library tests, `hoverAtIndex` / `clickAtIndex` / `hoverUntilTooltip` / `dragSelection` drive gestures, and `createDefaultTooltipAccessor` reads the built-in tooltip. The `data-attr` selectors are a public contract. [docs/TESTING.md](./src/docs/TESTING.md)
+Import helpers from `@posthog/quill-charts/testing` (jsdom only): `setupChartTests()` sets up a test file, `findChart()` waits for the chart and returns an accessor over its stable `data-attr` hooks, and `chart.hoverTooltip(i)` reads the tooltip at a label. `renderChart` adds tooltip-context capture for library tests. The `data-attr` selectors are a public contract. [docs/TESTING.md](./src/docs/TESTING.md)
## Docs index
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
index 9d5ec5fa5ff0..a703ed51f53a 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
@@ -5,6 +5,7 @@ import { useChartLayout } from '../../core/chart-context'
import type { BarScaleSet, StackedBand } from '../../core/scales'
import type { Series, TooltipConfig, TooltipContext } from '../../core/types'
import { DefaultTooltip } from '../../overlays/DefaultTooltip'
+import { useTooltipCapture } from '../../overlays/Tooltip'
import {
type BarLayout,
findVisibleStackedSegment,
@@ -36,6 +37,7 @@ export function BarTooltip<Meta>({
tooltipConfig,
}: BarTooltipProps<Meta>): React.ReactElement | null {
const { scales, labels } = useChartLayout()
+ const captureTooltip = useTooltipCapture<Meta>()
const { hitArea = 'bar', ...defaultTooltipConfig } = tooltipConfig ?? {}
const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
if (d3Scales && ctx.hoverPosition && ctx.dataIndex >= 0) {
@@ -53,6 +55,7 @@ export function BarTooltip<Meta>({
if (!narrowed) {
return null
}
+ captureTooltip(narrowed)
return <>{userTooltip ? userTooltip(narrowed) : <DefaultTooltip {...narrowed} {...defaultTooltipConfig} />}</>
}
return <>{userTooltip ? userTooltip(ctx) : <DefaultTooltip {...ctx} {...defaultTooltipConfig} />}</>
diff --git a/packages/quill/packages/charts/src/charts/BarList/BarList.test.tsx b/packages/quill/packages/charts/src/charts/BarList/BarList.test.tsx
index 769f0c033810..3e291308207a 100644
--- a/packages/quill/packages/charts/src/charts/BarList/BarList.test.tsx
+++ b/packages/quill/packages/charts/src/charts/BarList/BarList.test.tsx
@@ -21,8 +21,7 @@ describe('BarList', () => {
{ name: 'an explicit total', total: 1000, valueText: '10% · 100' },
])('shows the hovered row in the tooltip and its share of $name', async ({ total, valueText }) => {
const { chart } = renderChart(
- <BarList series={ROWS} theme={THEME} total={total} config={{ valueDisplay: 'both' }} />,
- { nativeTooltip: true }
+ <BarList series={ROWS} theme={THEME} total={total} config={{ valueDisplay: 'both' }} />
)
const tooltip = await waitForChartTooltip(3000, () => fireEvent.mouseMove(chart.element, INSIDE_B))
diff --git a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.test.tsx b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.test.tsx
index 52ff253a9578..e2d9fceeeb21 100644
--- a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.test.tsx
+++ b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.test.tsx
@@ -186,9 +186,6 @@ describe('BoxPlot', () => {
})
describe('tooltip rendering', () => {
- // `nativeTooltip: true` lets BoxPlotTooltip render its own DOM — the default mode
- // replaces the tooltip prop and short-circuits past it.
-
const SINGLE_SERIES: BoxPlotSeries[] = [
{
key: 'a',
@@ -198,9 +195,7 @@ describe('BoxPlot', () => {
]
it('renders the six stats in the canonical order (Max → p75 → Median → Mean → p25 → Min)', async () => {
- const { chart } = renderChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />, {
- nativeTooltip: true,
- })
+ const { chart } = renderChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />)
chart.hoverAtIndex(0)
const tooltipEl = await waitForChartTooltip()
const rowLabels = Array.from(tooltipEl.querySelectorAll('tr')).map((tr) =>
@@ -277,10 +272,7 @@ describe('BoxPlot', () => {
const series: BoxPlotSeries[] = [
{ key: 'a', label: 'A-label', data: [datum(override), datum(), datum()] },
]
- const { chart } = renderChart(
- <BoxPlot series={series} labels={LABELS} theme={THEME} config={config} />,
- { nativeTooltip: true }
- )
+ const { chart } = renderChart(<BoxPlot series={series} labels={LABELS} theme={THEME} config={config} />)
chart.hoverAtIndex(0)
const tooltipEl = await waitForChartTooltip()
const rendered = Array.from(tooltipEl.querySelectorAll('tr')).map((tr) => [
@@ -292,9 +284,7 @@ describe('BoxPlot', () => {
)
it('renders the values in the canonical row order', async () => {
- const { chart } = renderChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />, {
- nativeTooltip: true,
- })
+ const { chart } = renderChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />)
chart.hoverAtIndex(0)
const tooltipEl = await waitForChartTooltip()
const values = Array.from(tooltipEl.querySelectorAll('tr')).map((tr) =>
@@ -304,18 +294,14 @@ describe('BoxPlot', () => {
})
it('shows the x label in the header', async () => {
- const { chart } = renderChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />, {
- nativeTooltip: true,
- })
+ const { chart } = renderChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />)
chart.hoverAtIndex(0)
const tooltipEl = await waitForChartTooltip()
expect(tooltipEl.textContent).toContain('Mon')
})
it('renders one stat table per visible series when grouped (multi-series)', async () => {
- const { chart } = renderChart(<BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} />, {
- nativeTooltip: true,
- })
+ const { chart } = renderChart(<BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} />)
chart.hoverAtIndex(0)
const tooltipEl = await waitForChartTooltip()
// Per-series header labels show in grouped mode.
@@ -325,9 +311,7 @@ describe('BoxPlot', () => {
})
it('hides the per-series label when not grouped (single series)', async () => {
- const { chart } = renderChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />, {
- nativeTooltip: true,
- })
+ const { chart } = renderChart(<BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} />)
chart.hoverAtIndex(0)
const tooltipEl = await waitForChartTooltip()
const headers = Array.from(tooltipEl.querySelectorAll('.font-semibold')).map((el) => el.textContent)
@@ -341,8 +325,7 @@ describe('BoxPlot', () => {
(): React.ReactElement => <div data-attr="custom-boxplot-user-tooltip">custom</div>
)
const { chart } = renderChart(
- <BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} tooltip={userTooltip} />,
- { nativeTooltip: true }
+ <BoxPlot series={SINGLE_SERIES} labels={LABELS} theme={THEME} tooltip={userTooltip} />
)
chart.hoverAtIndex(0)
const tooltipEl = await waitForChartTooltip()
diff --git a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx
index 3aaead28f662..3e83e9dc71af 100644
--- a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx
@@ -41,11 +41,7 @@ describe('FunnelChart', () => {
})
it('tooltip header shows the step name and value is formatted as X.XX%', async () => {
- // nativeTooltip preserves config-level formatters (valueFormatter / labelFormatter);
- // the default renderChart path intercepts the tooltip prop and bypasses them.
- const { chart } = renderChart(<FunnelChart steps={STEPS} series={SERIES} theme={THEME} />, {
- nativeTooltip: true,
- })
+ const { chart } = renderChart(<FunnelChart steps={STEPS} series={SERIES} theme={THEME} />)
const step = dimensions.plotWidth / STEPS.length
// Hover at step-index 1 band center — same x as the onStepClick test, lands in control's sub-band.
const hoverX = dimensions.plotLeft + step * 1.3
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
index 1423afba7171..6daffe4ad854 100644
--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
@@ -19,6 +19,7 @@ import type {
TooltipContext,
} from '../../core/types'
import { DefaultTooltip } from '../../overlays/DefaultTooltip'
+import { useTooltipCapture } from '../../overlays/Tooltip'
import { findClosestSeriesKey } from '../../overlays/tooltipUtils'
import {
drawColumnHighlights,
@@ -438,12 +439,14 @@ function HeatmapInner({
const tooltipLabelFormatter = config?.tooltip?.labelFormatter
const tooltipValueFormatter = config?.tooltip?.valueFormatter
+ const captureTooltip = useTooltipCapture<HeatmapRowMeta>()
const renderTooltip = useMemo(
() =>
(ctx: HeatmapTooltipContext): React.ReactNode => {
// The base chart's `ctx.label` is the per-column key; restore the display label
// before it reaches either the custom or default tooltip.
const mapped = { ...ctx, label: resolveColumnLabel(ctx.label) }
+ captureTooltip(mapped)
if (tooltip) {
return tooltip(mapped)
}
@@ -466,7 +469,7 @@ function HeatmapInner({
/>
)
},
- [tooltip, resolveColumnLabel, tooltipLabelFormatter, tooltipValueFormatter]
+ [tooltip, resolveColumnLabel, tooltipLabelFormatter, tooltipValueFormatter, captureTooltip]
)
const baseConfig = useMemo<ChartConfig>(
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
index 4694365663dc..dc28133db4f3 100644
--- a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
@@ -12,6 +12,7 @@ import type {
Series,
TooltipContext,
} from '../../core/types'
+import { useTooltipCapture } from '../../overlays/Tooltip'
import { BarChart } from '../BarChart/BarChart'
import { PieTooltip } from '../PieChart/PieTooltip'
import { partValue, proportionLegendItems } from './proportion-bar-data'
@@ -147,6 +148,7 @@ function ProportionBarInner<Meta = unknown>({
// A percent layout hands the tooltip every segment as a 0..1 fraction. Narrow it to the hovered
// part with its raw value, which is the context a PieChart tooltip receives. Reads the value
// already computed for `barSeries` instead of rescanning the part's data on every hover.
+ const captureTooltip = useTooltipCapture<Meta>()
const renderTooltip = useCallback(
(ctx: TooltipContext<Meta>): React.ReactNode => {
const entry = ctx.seriesData.find((d) => d.series.key === ctx.hoveredSeriesKey)
@@ -162,9 +164,10 @@ function ProportionBarInner<Meta = unknown>({
dataIndex: series.indexOf(original),
seriesData: [{ ...entry, series: part, value, fraction: fractionOf(value) }],
}
+ captureTooltip(partCtx)
return tooltip ? tooltip(partCtx) : <PieTooltip ctx={partCtx} valueFormatter={valueFormatter} />
},
- [tooltip, series, seriesByKey, colorByKey, valueByKey, fractionOf, valueFormatter]
+ [tooltip, series, seriesByKey, colorByKey, valueByKey, fractionOf, valueFormatter, captureTooltip]
)
const handlePointClick = useCallback(
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
index d636a166cf49..b81a20b564fe 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
@@ -85,8 +85,7 @@ describe('SankeyChart', () => {
theme={THEME}
onNodeClick={onNodeClick}
onHoverChange={onHoverChange}
- />,
- { nativeTooltip: true }
+ />
)
await waitFor(() => {
fireEvent.mouseMove(chart.element, nodeCenter('a'))
@@ -148,8 +147,7 @@ describe('SankeyChart', () => {
theme={THEME}
onNodeClick={onNodeClick}
onHoverChange={onHoverChange}
- />,
- { nativeTooltip: true }
+ />
)
// A tap sends no mousemove first, so nothing is hovered when the click arrives. jsdom has
// no PointerEvent, so the pointer type rides on a MouseEvent React reads it from.
@@ -215,8 +213,7 @@ describe('SankeyChart', () => {
const { chart } = renderChart(
<SankeyChart nodes={NODES} links={LINKS} theme={THEME} onNodeClick={onNodeClick}>
<button data-hog-charts-interactive-overlay>overlay</button>
- </SankeyChart>,
- { nativeTooltip: true }
+ </SankeyChart>
)
await waitFor(() => {
fireEvent.mouseMove(chart.element, nodeCenter('a'))
@@ -277,9 +274,7 @@ describe('SankeyChart', () => {
})
it('shows the node tooltip when the pointer is over its label, not the ribbon under it', async () => {
- const { chart } = renderChart(<SankeyChart nodes={NODES} links={LINKS} theme={THEME} />, {
- nativeTooltip: true,
- })
+ const { chart } = renderChart(<SankeyChart nodes={NODES} links={LINKS} theme={THEME} />)
// Right of the Start node, inside its label and over the Start -> Tool A ribbon.
const start = nodeCenter('start')
await waitFor(() => {
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx
index 69a436eb90f9..2e12598c0158 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx
@@ -41,8 +41,7 @@ function renderScatter(props: Partial<React.ComponentProps<typeof ScatterChart>>
theme={THEME}
config={{ margins: MARGINS, xAxis: { label: 'Reads' }, yAxis: { label: 'Writes' }, ...props.config }}
{...props}
- />,
- { nativeTooltip: true }
+ />
)
}
@@ -169,8 +168,7 @@ describe('ScatterChart', () => {
xAxis: { domain: [0, 100] },
yAxis: { scaleType: 'log', domain: [1, 100] },
}}
- />,
- { nativeTooltip: true }
+ />
)
// A log scale clamps, so the excluded point would otherwise sit hoverable on the top edge.
await waitForChartTooltip(3000, () => {
@@ -200,8 +198,7 @@ describe('ScatterChart', () => {
{ key: 'orgs', label: 'Orgs', points: [{ x: 100, y: 100, label: 'Hedgebox', meta: { orgId: 'hb' } }] },
]
const { chart } = renderChart(
- <ScatterChart series={series} theme={THEME} config={{ margins: MARGINS }} onPointClick={onPointClick} />,
- { nativeTooltip: true }
+ <ScatterChart series={series} theme={THEME} config={{ margins: MARGINS }} onPointClick={onPointClick} />
)
await hoverPoint(chart.element, 100, 100)
fireEvent.click(chart.element)
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.test.tsx
index e07f68680543..1500d79572fc 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.test.tsx
@@ -290,8 +290,6 @@ describe('TimeSeriesComboChart', () => {
expect(tooltip.seriesData.map((s) => s.series.key).sort()).toEqual(['bar', 'line'])
})
- // `nativeTooltip` lets the chart render its own DefaultTooltip from config (the harness's
- // default tooltip-prop interception would otherwise bypass the config formatters).
it('formats the built-in tooltip rows with config.tooltip.valueFormatter', async () => {
const { chart } = renderChart(
<TimeSeriesComboChart
@@ -299,8 +297,7 @@ describe('TimeSeriesComboChart', () => {
labels={LABELS}
theme={THEME}
config={{ tooltip: { valueFormatter: (v) => `$${v}` } }}
- />,
- { nativeTooltip: true }
+ />
)
chart.hoverAtIndex(1)
const tooltip = await waitForChartTooltip()
@@ -314,8 +311,7 @@ describe('TimeSeriesComboChart', () => {
labels={LABELS}
theme={THEME}
config={{ tooltip: { showTotal: true, totalLabel: 'Sum' } }}
- />,
- { nativeTooltip: true }
+ />
)
chart.hoverAtIndex(1)
const tooltip = await waitForChartTooltip()
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
index 6579e4540872..423f3c3da4fd 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -98,8 +98,7 @@ describe('TimeSeriesLineChart', () => {
labels={labels}
theme={THEME}
config={{ xAxis: { timezone: 'UTC' } }}
- />,
- { nativeTooltip: true }
+ />
)
expect(chart.xTicks().some((tick) => /Jun \d+/.test(tick))).toBe(true)
diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsx
index 4106299a6e92..7679d7fc5c65 100644
--- a/packages/quill/packages/charts/src/core/Chart.tsx
+++ b/packages/quill/packages/charts/src/core/Chart.tsx
@@ -458,6 +458,7 @@ export function Chart<Meta = unknown>({
}
crosshair={!!onDateRangeZoom || !!onAreaSelect}
ariaLabel={ariaLabel}
+ labelCount={labels.length}
handlers={handlers}
showOverlay={!!(dimensions && scales)}
>
diff --git a/packages/quill/packages/charts/src/core/chart-shell.tsx b/packages/quill/packages/charts/src/core/chart-shell.tsx
index a46c3896608e..10192e89eca5 100644
--- a/packages/quill/packages/charts/src/core/chart-shell.tsx
+++ b/packages/quill/packages/charts/src/core/chart-shell.tsx
@@ -39,6 +39,8 @@ export interface ChartShellProps {
/** Show the crosshair cursor — a drag gesture (e.g. drag-to-zoom) is available. */
crosshair?: boolean
ariaLabel: string
+ /** Number of x labels. Tests read it to hover a label by index. */
+ labelCount?: number
handlers: Required<Pick<React.DOMAttributes<HTMLDivElement>, 'onMouseMove' | 'onMouseLeave' | 'onClick'>> &
Pick<React.DOMAttributes<HTMLDivElement>, 'onMouseDown' | 'onPointerDown'>
/** Render the overlay layer — bases gate this on layout readiness (dimensions + scales). */
@@ -67,6 +69,7 @@ export function ChartShell({
pointer,
crosshair = false,
ariaLabel,
+ labelCount,
handlers,
showOverlay,
children,
@@ -76,6 +79,7 @@ export function ChartShell({
ref={wrapperRef}
className={[WRAPPER_CLASS, cursorClass(pointer, crosshair), className].filter(Boolean).join(' ')}
data-attr={dataAttr}
+ data-hog-charts-label-count={labelCount}
onMouseDown={handlers.onMouseDown}
onMouseMove={handlers.onMouseMove}
onMouseLeave={handlers.onMouseLeave}
diff --git a/packages/quill/packages/charts/src/docs/TESTING.md b/packages/quill/packages/charts/src/docs/TESTING.md
index b0e7a6768fc2..afddf6f3af38 100644
--- a/packages/quill/packages/charts/src/docs/TESTING.md
+++ b/packages/quill/packages/charts/src/docs/TESTING.md
@@ -2,35 +2,36 @@
Two audiences:
-- **Embedding hog-charts** in your own component or page and writing tests for that surrounding code → [Testing code that uses hog-charts](#testing-code-that-uses-hog-charts).
+- **Embedding a chart** in your own component or page and writing tests for that surrounding code → [Testing code that uses charts](#testing-code-that-uses-charts).
- **Working on the library itself** — chart types, overlays, the draw loop → [Testing the library itself](#testing-the-library-itself).
The contract both sections rely on: the `data-attr` selectors and the `ChartAccessor` are stable. Renaming a `data-attr` is a breaking change — it breaks consumers' tests as much as renaming an exported type. JSdom's canvas is a stub, so canvas pixels aren't a viable test surface anyway — assertions go through the DOM.
-## Testing code that uses hog-charts
+## Testing code that uses charts
-You've rendered a tree that contains a chart somewhere — a dashboard, an insight scene, a custom panel. Use your own `render` (or RTL wrappers like kea-test-utils) and read the chart with `getChart(scope)`:
+You've rendered a tree that contains a chart somewhere: a dashboard, an insight scene, a custom panel. Render it your usual way, then read the chart with `findChart()`:
```tsx
import { render } from '@testing-library/react'
-import { ensureJsdom, getChart, hoverAtIndex, waitForChartTooltip } from '@posthog/quill-charts/testing'
+import { findChart, setupChartTests } from '@posthog/quill-charts/testing'
-ensureJsdom()
+setupChartTests()
it('renders the goal line on the dashboard chart', async () => {
- const { container } = render(<Dashboard />)
- const chart = getChart(container)
+ render(<Dashboard />)
+ const chart = await findChart()
expect(chart.referenceLines()).toHaveLength(1)
- expect(chart.yTicks()).toContain('0')
- hoverAtIndex(chart.element, 1, LABELS.length)
- const tooltip = await waitForChartTooltip()
- expect(tooltip.textContent).toContain('Tue')
+ const tooltip = await chart.hoverTooltip(1)
+ expect(tooltip.label()).toBe('Tue')
+ expect(tooltip.value('Pageviews')).toBe('134')
})
```
-`ensureJsdom()` installs the jsdom mocks (`ResizeObserver`, `getBoundingClientRect`) and a synchronous `requestAnimationFrame` shim. It's idempotent — call it once at the top of a file and forget about it.
+- `setupChartTests()` registers the hooks every chart test needs: jsdom mocks for `ResizeObserver` and `getBoundingClientRect`, synchronous animation frames, and cleanup after each test.
+- `findChart()` waits for the chart to render. Pass `seriesCount` to wait for a specific series count, or `scope` when the page has more than one chart. `getChart()` is the synchronous version.
+- `chart.hoverTooltip(i)` hovers the label at index `i` until the tooltip shows its content, then reads it as a `DefaultTooltip`. For a custom tooltip, read `tooltip.element`.
The accessor surface (full list in `testing/accessor.ts`):
@@ -56,14 +57,13 @@ chart.sankeyNodeLabels() // ['/home', '/pricing', …] Sankey node labels in lay
chart.sankeyColumnLabels() // ['Step 1', 'Step 2', …] Sankey column headers, left to right
```
-For interactions, use the module-level helpers:
+Gestures work under any wrapper, because the chart records its label count on its root:
-- `hoverAtIndex(wrapper, i, totalLabels)` — `mouseMove` over labels[i].
-- `clickAtIndex(wrapper, i, totalLabels)` — hover-then-click. Resolves after the click handler runs.
-- `dragSelection(wrapper, fromIndex, toIndex, totalLabels)` — simulates a drag-to-zoom gesture between two label indices.
-- `waitForChartTooltip()` — resolves with the rendered tooltip element once it mounts in the `FloatingPortal`.
+- `chart.hoverAtIndex(i)` fires one `mouseMove` over the label at index `i`, without waiting.
+- `await chart.clickAtIndex(i)` hovers, then clicks. It resolves after the click handler runs.
+- `chart.dragSelection(from, to)` drags between two label indices, for drag-to-zoom.
-`chart.hoverAtIndex(i)`, `chart.dragSelection(i, j)`, and `chart.waitForTooltip()` (returning a structured `TooltipSnapshot` with `seriesData`, `isPinned`, etc.) need `renderChart` — they read label count and the captured `TooltipContext` that only the library's own render wrapper sets up. For most consumer tests, DOM assertions through the accessor are enough.
+`chart.waitForTooltip()` returns the structured `TooltipContext` (`seriesData`, `isPinned` and so on). It needs `renderChart`, which captures that context.
## Testing the library itself
@@ -88,7 +88,7 @@ describe('LineChart', () => {
})
```
-`renderChart` is `render` plus three things consumers don't need: auto-`ensureJsdom`, tooltip-context capture (so `chart.waitForTooltip()` returns the structured `TooltipContext`), and a cached `labels.length` (so `chart.hoverAtIndex(i)` doesn't take a `totalLabels` argument).
+`renderChart` is `render` plus the jsdom mocks and tooltip-context capture, so `chart.waitForTooltip()` returns the context the chart's tooltip content received.
### Interactions and tooltip context
diff --git a/packages/quill/packages/charts/src/docs/interactions.md b/packages/quill/packages/charts/src/docs/interactions.md
index 71b35479f8c1..1e649e5e9444 100644
--- a/packages/quill/packages/charts/src/docs/interactions.md
+++ b/packages/quill/packages/charts/src/docs/interactions.md
@@ -50,8 +50,8 @@ See [legend.md](./legend.md).
## Testing interactions
-`hoverAtIndex`, `clickAtIndex`, `hoverUntilTooltip`, and `dragSelection` from `@posthog/quill-charts/testing` drive these gestures in jsdom.
-`hoverUntilTooltip` and `clickAtIndex` re-dispatch until the tooltip portal mounts, because the chart drops events fired before it commits its scales.
+The chart accessor from `@posthog/quill-charts/testing` drives these gestures in jsdom: `chart.hoverAtIndex`, `chart.hoverTooltip`, `chart.clickAtIndex` and `chart.dragSelection`.
+`hoverTooltip` and `clickAtIndex` re-dispatch until the tooltip portal mounts, because the chart drops events fired before it commits its scales.
Both default to a 3000ms budget.
Pass an explicit `timeout` whenever the call sits behind another wait in the same test; two full-length waits chained together exceed Jest's 5000ms per-test budget, so give the pair one shared deadline.
See [TESTING.md](./TESTING.md).
diff --git a/packages/quill/packages/charts/src/docs/tooltips.md b/packages/quill/packages/charts/src/docs/tooltips.md
index 8d80d40d7d80..e868bda04d73 100644
--- a/packages/quill/packages/charts/src/docs/tooltips.md
+++ b/packages/quill/packages/charts/src/docs/tooltips.md
@@ -67,7 +67,7 @@ Mouse hover and click behavior is unchanged; the split lives in `useChartInterac
## Testing
For a chart mounted through `renderChart`, `chart.waitForTooltip()` returns a structured `TooltipSnapshot`.
-For a chart rendered anywhere else (a product scene), read the tooltip from the DOM: `getChartTooltip()` and `waitForChartTooltip()` return the portal element, and `createChartTooltipAccessor(el)` wraps it as `{ element, isPinned }`.
-`createDefaultTooltipAccessor(el)` reads a rendered `DefaultTooltip` through its `data-attr="hog-chart-tooltip-*"` hooks: `label()`, `rows()`, `value(seriesLabel)`, `swatchColors()`, `total()`.
+For a chart rendered anywhere else (a product scene), `await chart.hoverTooltip(i)` reads a rendered `DefaultTooltip` through its `data-attr="hog-chart-tooltip-*"` hooks: `label()`, `rows()`, `value(seriesLabel)`, `swatchColors()`, `total()`.
+For a custom tooltip, read `tooltip.element`, or wrap a portal element from `waitForChartTooltip()` with `createChartTooltipAccessor(el)`.
Those attributes are a testing contract; keep the accessor and the component in sync.
All helpers come from `@posthog/quill-charts/testing`.
diff --git a/packages/quill/packages/charts/src/overlays/Tooltip.tsx b/packages/quill/packages/charts/src/overlays/Tooltip.tsx
index 478b0e39c8e0..8d2172543448 100644
--- a/packages/quill/packages/charts/src/overlays/Tooltip.tsx
+++ b/packages/quill/packages/charts/src/overlays/Tooltip.tsx
@@ -1,5 +1,5 @@
import { autoUpdate, flip, FloatingPortal, offset, shift, useFloating, type VirtualElement } from '@floating-ui/react'
-import React, { useLayoutEffect, useMemo } from 'react'
+import React, { createContext, useContext, useLayoutEffect, useMemo } from 'react'
import { useChartLayout } from '../core/chart-context'
import type { TooltipContext } from '../core/types'
@@ -10,6 +10,15 @@ interface TooltipProps<Meta> {
placement?: 'follow-data' | 'top' | 'cursor'
}
+const TooltipCaptureContext = createContext<((ctx: TooltipContext) => void) | null>(null)
+export const TooltipCaptureProvider = TooltipCaptureContext.Provider
+const noCapture = (): void => {}
+
+/** Test seam for `renderChart`. Called during render, so a chart that narrows the context after `Tooltip` wins. */
+export function useTooltipCapture<Meta>(): (ctx: TooltipContext<Meta>) => void {
+ return (useContext(TooltipCaptureContext) ?? noCapture) as (ctx: TooltipContext<Meta>) => void
+}
+
const TOOLTIP_MIDDLEWARE = [offset(12), flip(), shift({ padding: 8 })]
const DEFAULT_TOOLTIP_Z_INDEX = 9999
@@ -19,6 +28,7 @@ export function Tooltip<Meta = unknown>({
placement = 'follow-data',
}: TooltipProps<Meta>): React.ReactElement {
const { theme } = useChartLayout()
+ useTooltipCapture<Meta>()(context)
const zIndex = theme.tooltipZIndex ?? DEFAULT_TOOLTIP_Z_INDEX
const { left: canvasLeft, top: canvasTop } = context.canvasBounds
// `cursor` follows the mouse (falling back to the data anchor on non-mousemove rebuilds);
diff --git a/packages/quill/packages/charts/src/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.ts
index 3af7d9947117..a7d6cfe96bc4 100644
--- a/packages/quill/packages/charts/src/testing/accessor.ts
+++ b/packages/quill/packages/charts/src/testing/accessor.ts
@@ -6,12 +6,16 @@
// contract — renaming them breaks consumers' tests. Keep in sync with the
// overlay components that emit them.
-import { act, fireEvent } from '@testing-library/react'
+import { act, fireEvent, waitFor } from '@testing-library/react'
import type { TooltipContext } from '../core/types'
-import { dragSelection } from './interactions'
-import { clientForIndex } from './jsdom'
-import { type ChartTooltipAccessor, waitForChartTooltip } from './tooltip'
+import { clickAtIndex, dragSelection, hoverAtIndex, hoverUntilTooltip } from './interactions'
+import {
+ type ChartTooltipAccessor,
+ createDefaultTooltipAccessor,
+ type DefaultTooltipAccessor,
+ waitForChartTooltip,
+} from './tooltip'
/** A single entry of `TooltipContext.seriesData`. */
type TooltipSeriesEntry<Meta = unknown> = TooltipContext<Meta>['seriesData'][number]
@@ -67,7 +71,7 @@ export interface ChartAccessor<Meta = unknown> {
/** The static (data) canvas, as opposed to the `aria-hidden` hover overlay. */
canvas: HTMLCanvasElement
/** Number of non-excluded data series rendered (read from the chart's aria-label). */
- seriesCount: number
+ readonly seriesCount: number
/** Visible y-axis tick labels (left axis). */
yTicks(): string[]
/** Visible right y-axis tick labels (multi-axis charts). */
@@ -105,13 +109,14 @@ export interface ChartAccessor<Meta = unknown> {
sankeyColumnLabels(): string[]
/** Annotation badges currently rendered. */
annotationBadges(): HTMLElement[]
- /** Fire a `mouseMove` over the data point at `index`. Only available when the chart was
- * rendered via `renderChart` (it reads label count from `ui.props.labels`); the
- * module-level `hoverAtIndex(wrapper, index, totalLabels)` is the explicit alternative. */
+ /** Fire one `mouseMove` over the label at `index`, without waiting for a tooltip. */
hoverAtIndex(index: number): void
+ /** Hover the label at `index` until the tooltip shows its content, then read it as a `DefaultTooltip`.
+ * For a custom tooltip, read `tooltip.element`. */
+ hoverTooltip(index: number, timeout?: number): Promise<DefaultTooltipAccessor>
/** Hover at the index, wait for the tooltip to settle, then click. Mirrors the
* hover-then-click sequence the chart's onClick handler relies on. */
- clickAtIndex(index: number): Promise<void>
+ clickAtIndex(index: number, timeout?: number): Promise<void>
dragSelection(fromIndex: number, toIndex: number): void
/** Wait for the tooltip to mount, then return a snapshot — every `TooltipContext` field
* plus the rendered portal element and an `isPinned` getter. Only available when the
@@ -123,9 +128,30 @@ export interface GetChartOptions<Meta = unknown> {
/** Returns the most recent `TooltipContext` the chart computed (set up by `renderChart`'s
* capturing tooltip wrapper). When omitted, `chart.waitForTooltip()` throws. */
getLastTooltipContext?: () => TooltipContext<Meta> | null
- /** Total label count for `chart.hoverAtIndex` / `chart.clickAtIndex`. When omitted, those
- * methods throw — use the module-level `hoverAtIndex` instead. */
- totalLabels?: number
+}
+
+export interface FindChartOptions {
+ scope?: HTMLElement
+ seriesCount?: number
+ timeout?: number
+}
+
+export async function findChart<Meta = unknown>({
+ scope = document.body,
+ seriesCount,
+ timeout = 3000,
+}: FindChartOptions = {}): Promise<ChartAccessor<Meta>> {
+ let chart!: ChartAccessor<Meta>
+ await waitFor(
+ () => {
+ chart = getChart<Meta>(scope)
+ if (seriesCount !== undefined && chart.seriesCount !== seriesCount) {
+ throw new Error(`Expected ${seriesCount} series, the chart has ${chart.seriesCount}`)
+ }
+ },
+ { timeout }
+ )
+ return chart
}
const SERIES_COUNT_RE = /Chart with (\d+) data series/i
@@ -181,16 +207,23 @@ export function getChart<Meta = unknown>(
throw new Error('quill-charts canvas has no parent wrapper')
}
- const ariaLabel = canvas.getAttribute('aria-label') ?? ''
- const match = SERIES_COUNT_RE.exec(ariaLabel)
- const seriesCount = match ? Number(match[1]) : 0
+ const { getLastTooltipContext } = options
- const { getLastTooltipContext, totalLabels } = options
+ const labelCount = (): number => {
+ const count = Number(wrapper.dataset.hogChartsLabelCount)
+ if (!Number.isFinite(count)) {
+ throw new Error('This chart has no labels to hover by index')
+ }
+ return count
+ }
return {
element: wrapper,
canvas,
- seriesCount,
+ get seriesCount(): number {
+ const match = SERIES_COUNT_RE.exec(canvas.getAttribute('aria-label') ?? '')
+ return match ? Number(match[1]) : 0
+ },
get hasRightAxis(): boolean {
return wrapper.querySelectorAll('[data-attr="hog-chart-axis-tick-yr"]').length > 0
},
@@ -262,26 +295,26 @@ export function getChart<Meta = unknown>(
),
annotationBadges: () => Array.from(wrapper.querySelectorAll<HTMLElement>('.AnnotationsBadge')),
hoverAtIndex(index: number): void {
- if (totalLabels === undefined) {
- throw new Error('chart.hoverAtIndex requires renderChart (which captures labels.length)')
- }
- fireEvent.mouseMove(wrapper, clientForIndex(index, totalLabels))
+ hoverAtIndex(wrapper, index, labelCount())
},
- async clickAtIndex(index: number): Promise<void> {
- if (totalLabels === undefined) {
- throw new Error('chart.clickAtIndex requires renderChart (which captures labels.length)')
- }
- fireEvent.mouseMove(wrapper, clientForIndex(index, totalLabels))
- // Wait for the hover state to flush — the click handler reads live tooltipCtx
- // synchronously to choose between pinning and onPointClick.
- await waitForChartTooltip()
- fireEvent.click(wrapper)
+ async hoverTooltip(index: number, timeout?: number): Promise<DefaultTooltipAccessor> {
+ const element = await hoverUntilTooltip(wrapper, index, labelCount(), timeout)
+ // The portal can mount a commit before its content does.
+ await waitFor(
+ () => {
+ if (!element.textContent?.trim()) {
+ throw new Error('tooltip has no content yet')
+ }
+ },
+ { timeout }
+ )
+ return createDefaultTooltipAccessor(element)
+ },
+ async clickAtIndex(index: number, timeout?: number): Promise<void> {
+ await clickAtIndex(wrapper, index, labelCount(), timeout)
},
dragSelection(fromIndex: number, toIndex: number): void {
- if (totalLabels === undefined) {
- throw new Error('chart.dragSelection requires renderChart (which captures labels.length)')
- }
- dragSelection(wrapper, fromIndex, toIndex, totalLabels)
+ dragSelection(wrapper, fromIndex, toIndex, labelCount())
},
async waitForTooltip(timeout?: number): Promise<TooltipSnapshot<Meta>> {
const element = await waitForChartTooltip(timeout)
diff --git a/packages/quill/packages/charts/src/testing/index.ts b/packages/quill/packages/charts/src/testing/index.ts
index e432511efe97..f48a78469340 100644
--- a/packages/quill/packages/charts/src/testing/index.ts
+++ b/packages/quill/packages/charts/src/testing/index.ts
@@ -1,9 +1,8 @@
-export { dimensions, ensureJsdom, makeSeries, mockRect, setupJsdom, setupSyncRaf } from './jsdom'
+export { dimensions, ensureJsdom, makeSeries, mockRect, setupChartTests, setupJsdom, setupSyncRaf } from './jsdom'
export { clickAtIndex, dragSelection, hoverAtIndex, hoverUntilTooltip, rawDrag } from './interactions'
-export { getChart } from './accessor'
-export type { GetChartOptions, ChartAccessor, TooltipSnapshot } from './accessor'
+export { findChart, getChart } from './accessor'
+export type { ChartAccessor, FindChartOptions, GetChartOptions, TooltipSnapshot } from './accessor'
export { renderChart } from './render'
-export type { RenderChartOptions } from './render'
export { makeOverlayContext, renderOverlayInChart } from './overlay'
export type { OverlayContextOverrides } from './overlay'
export {
diff --git a/packages/quill/packages/charts/src/testing/jsdom.ts b/packages/quill/packages/charts/src/testing/jsdom.ts
index cac844d75279..b0e7c86dab07 100644
--- a/packages/quill/packages/charts/src/testing/jsdom.ts
+++ b/packages/quill/packages/charts/src/testing/jsdom.ts
@@ -1,6 +1,9 @@
+import { cleanup } from '@testing-library/react'
+
import { buildDimensions } from '../core/canvas-size'
import { DEFAULT_MARGINS } from '../core/hooks/useChartMargins'
import type { ChartDimensions, ResolvedSeries, Series } from '../core/types'
+import { TOOLTIP_SELECTOR } from './tooltip'
export const mockRect: DOMRect = {
x: 0,
@@ -95,3 +98,17 @@ export function ensureJsdom(): void {
setupJsdom()
setupSyncRaf()
}
+
+/** Registers hooks for the jsdom mocks, synchronous animation frames and cleanup. Call once per file or `describe`. */
+export function setupChartTests(): void {
+ let restore: (() => void)[] = []
+ beforeEach(() => {
+ restore = [setupJsdom(), setupSyncRaf()]
+ })
+ afterEach(() => {
+ cleanup()
+ // `cleanup` doesn't always reach the tooltip's FloatingPortal.
+ document.querySelectorAll(TOOLTIP_SELECTOR).forEach((el) => el.remove())
+ restore.forEach((fn) => fn())
+ })
+}
diff --git a/packages/quill/packages/charts/src/testing/render.tsx b/packages/quill/packages/charts/src/testing/render.tsx
index f9d1a5a245d8..d7e2428d7e89 100644
--- a/packages/quill/packages/charts/src/testing/render.tsx
+++ b/packages/quill/packages/charts/src/testing/render.tsx
@@ -1,53 +1,33 @@
import { cleanup, render, type RenderResult } from '@testing-library/react'
-import React, { type ReactElement, type ReactNode } from 'react'
+import type { ReactElement } from 'react'
import type { TooltipContext } from '../core/types'
-import { DefaultTooltip } from '../overlays/DefaultTooltip'
-import { getChart, type ChartAccessor } from './accessor'
+import { TooltipCaptureProvider } from '../overlays/Tooltip'
+import { type ChartAccessor, getChart } from './accessor'
import { ensureJsdom } from './jsdom'
import { TOOLTIP_SELECTOR } from './tooltip'
-export interface RenderChartOptions {
- /** Skip the tooltip-prop override so the chart renders its own tooltip. Context capture
- * via `chart.waitForTooltip()` is unavailable in this mode. */
- nativeTooltip?: boolean
-}
-
/** Render a quill-charts component and return Testing Library's `RenderResult` with a `chart`
* accessor attached. Throws if the rendered tree doesn't contain a quill-charts canvas.
*
* Sets up the jsdom mocks + sync RAF on first call (idempotent), so tests don't need a
* beforeEach for those. Also calls `cleanup()` and removes any leftover tooltip portal
* before each render — RTL's auto-cleanup doesn't always reach `FloatingPortal` children. */
-export function renderChart<Meta = unknown>(
- ui: ReactElement,
- options: RenderChartOptions = {}
-): RenderResult & { chart: ChartAccessor<Meta> } {
+export function renderChart<Meta = unknown>(ui: ReactElement): RenderResult & { chart: ChartAccessor<Meta> } {
ensureJsdom()
cleanup()
document.querySelectorAll(TOOLTIP_SELECTOR).forEach((el) => el.remove())
- const props = ui.props as { tooltip?: (ctx: TooltipContext<Meta>) => ReactNode; labels?: string[] }
-
- // Intercept the `tooltip` render prop so `chart.waitForTooltip()` exposes the structured
- // `TooltipContext` the chart computed. Falls through to DefaultTooltip when no consumer
- // tooltip is supplied, matching the chart's natural default.
let lastTooltipContext: TooltipContext<Meta> | null = null
- let toRender: ReactElement = ui
- if (!options.nativeTooltip) {
- const userTooltip = props.tooltip
- const captureTooltip = (ctx: TooltipContext<Meta>): ReactNode => {
- lastTooltipContext = ctx
- return userTooltip ? userTooltip(ctx) : <DefaultTooltip {...(ctx as TooltipContext)} />
- }
- toRender = React.cloneElement(ui, { tooltip: captureTooltip })
+ const capture = (ctx: TooltipContext): void => {
+ lastTooltipContext = ctx as TooltipContext<Meta>
}
- const result = render(toRender)
+ // A `wrapper` survives `rerender`, which would drop a provider written around `ui`.
+ const result = render(ui, {
+ wrapper: ({ children }) => <TooltipCaptureProvider value={capture}>{children}</TooltipCaptureProvider>,
+ })
return {
...result,
- chart: getChart<Meta>(result.container, {
- getLastTooltipContext: () => lastTooltipContext,
- totalLabels: props.labels?.length,
- }),
+ chart: getChart<Meta>(result.container, { getLastTooltipContext: () => lastTooltipContext }),
}
}
diff --git a/products/marketing_analytics/frontend/dashboard/charts/MetricChart.test.tsx b/products/marketing_analytics/frontend/dashboard/charts/MetricChart.test.tsx
index 447042ccfc7a..1b6afe2bd02a 100644
--- a/products/marketing_analytics/frontend/dashboard/charts/MetricChart.test.tsx
+++ b/products/marketing_analytics/frontend/dashboard/charts/MetricChart.test.tsx
@@ -37,8 +37,7 @@ describe('MetricChart', () => {
{ key: 'upper', label: 'Upper line', data: [200, 200, 200] },
]}
onFocus={onFocus}
- />,
- { nativeTooltip: true }
+ />
)
await clickAtIndex(chart.element, 1, props.labels.length)
@@ -52,8 +51,7 @@ describe('MetricChart', () => {
{...props}
format="percentage"
series={[{ key: 'email', label: 'Email', data: [0, 0.42, 1] }]}
- />,
- { nativeTooltip: true }
+ />
)
const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 1, props.labels.length))
@@ -63,8 +61,7 @@ describe('MetricChart', () => {
it('shows the supplied error instead of stale data and hides it during retry', () => {
const { container, rerender, getByText, queryByText } = renderChart(
- <MetricChart {...props} series={[{ key: 'email', label: 'Email', data: [0, 12, 8] }]} />,
- { nativeTooltip: true }
+ <MetricChart {...props} series={[{ key: 'email', label: 'Email', data: [0, 12, 8] }]} />
)
rerender(
<MetricChart