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.

chore(quill-charts): publish the testing entry and tidy the chart accessor (#125304)

Sam Pennington0fc16358bf58
diff --git a/.agents/skills/working-with-charts/SKILL.md b/.agents/skills/working-with-charts/SKILL.md
index 73e80195ac6a..cb0c47f682ca 100644
--- a/.agents/skills/working-with-charts/SKILL.md
+++ b/.agents/skills/working-with-charts/SKILL.md
@@ -52,6 +52,6 @@ Load only the relevant topic:
Render at the intended container sizes and in light and dark themes.
Check missing values, long labels, and any interactions you changed.
-Extend relevant tests and stories; use the [consumer testing guide](../../../packages/quill/packages/charts/src/docs/TESTING.md#testing-code-that-uses-hog-charts) for chart accessors.
+Extend relevant tests and stories; use the [consumer testing guide](../../../packages/quill/packages/charts/src/docs/TESTING.md#testing-code-that-uses-charts) for chart accessors.
Keep detailed API behavior in the package docs rather than copying it into this skill.
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx
index ad0af7b1c6ba..611ae70d5f19 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx
@@ -3,7 +3,7 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
+import { getChart, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
import { BIField } from '~/queries/schema/schema-business-intelligence'
import { ChartSettings, NodeKind } from '~/queries/schema/schema-general'
@@ -61,9 +61,9 @@ const baseProps = (
// quill PieChart's flaky hover/click interaction tests. Each slice renders one <div> per line
// (label and/or value), so we read the lines per slice rather than the concatenated text.
function sliceLabelLines(): string[][] {
- return Array.from(document.querySelectorAll('[data-attr="hog-chart-pie-slice-label"]')).map((el) =>
- Array.from(el.querySelectorAll('div')).map((line) => line.textContent!)
- )
+ return getChart()
+ .pie.sliceLabels()
+ .map((label) => label.lines)
}
async function waitForSlices(): Promise<void> {
@@ -259,7 +259,7 @@ describe('SqlPieGraph', () => {
// The legend is plain DOM outside the canvas, so it needs no canvas paint.
render(<SqlPieGraph {...baseProps({ showLegend: true }, [60, 40, 0, 0])} />)
- expect(document.querySelector('[data-attr="hog-chart-pie-legend"]')).toBeInTheDocument()
+ expect(getChart().legend()).toBeInTheDocument()
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(screen.getByText('beta')).toBeInTheDocument()
})
@@ -270,7 +270,7 @@ describe('SqlPieGraph', () => {
const user = userEvent.setup()
await waitForSlices()
- await user.click(within(document.querySelector('[data-attr="hog-chart-pie-legend"]')!).getByText('alpha'))
+ await user.click(within(getChart().legend()!).getByText('alpha'))
await waitFor(() => {
expect(sliceLabelLines()).toEqual([['alpha']])
@@ -280,7 +280,7 @@ describe('SqlPieGraph', () => {
rerender(<SqlPieGraph {...baseProps({ ...chartSettings, showLegend: false }, [60, 40, 0, 0])} />)
await waitFor(() => {
- expect(document.querySelector('[data-attr="hog-chart-pie-legend"]')).not.toBeInTheDocument()
+ expect(getChart().legend()).toBeNull()
expect(sliceLabelLines()).toEqual([['alpha'], ['beta']])
expect(screen.getByText('100')).toBeInTheDocument()
})
@@ -309,7 +309,7 @@ describe('SqlPieGraph', () => {
)
const swatchColors = Array.from(
- document.querySelectorAll<HTMLElement>('[data-attr="hog-chart-pie-legend"] span[aria-hidden="true"]')
+ getChart().legend()!.querySelectorAll<HTMLElement>('span[aria-hidden="true"]')
).map((el) => el.style.backgroundColor)
expect(screen.getByText('first')).toBeInTheDocument()
expect(swatchColors).toContain('rgb(170, 0, 0)')
diff --git a/frontend/src/test/insight-testing/README.md b/frontend/src/test/insight-testing/README.md
index a99559f7915a..00f508fb127c 100644
--- a/frontend/src/test/insight-testing/README.md
+++ b/frontend/src/test/insight-testing/README.md
@@ -58,6 +58,7 @@ renderWithInsights({
`getChart()` comes from `@posthog/quill-charts/testing`.
It reads the rendered chart through its stable DOM hooks: series count, axis ticks and titles, legend, reference lines and value labels.
+`annotationBadges()` reads the PostHog annotation badges on the chart.
See the [quill-charts testing guide](../../../../packages/quill/packages/charts/src/docs/TESTING.md).
`chart` wraps the gestures for insight charts, which render the InsightTooltip table:
diff --git a/frontend/src/test/insight-testing/elements.ts b/frontend/src/test/insight-testing/elements.ts
index bf45653a59d6..fb5d96cb2653 100644
--- a/frontend/src/test/insight-testing/elements.ts
+++ b/frontend/src/test/insight-testing/elements.ts
@@ -1,5 +1,7 @@
import { within } from '@testing-library/react'
+import { getChart } from '@posthog/quill-charts/testing'
+
// DOM element accessors and cleanup helpers for insight tests. These aren't
// user actions (those live in interactions.ts) — they're getters for asserting
// presence/absence and teardown helpers for roots rendered outside
@@ -47,3 +49,8 @@ export const personsModal = {
})
},
}
+
+/** Annotation badges rendered on the chart. */
+export function annotationBadges(chart = getChart()): HTMLElement[] {
+ return Array.from(chart.element.querySelectorAll<HTMLElement>('.AnnotationsBadge'))
+}
diff --git a/frontend/src/test/insight-testing/index.ts b/frontend/src/test/insight-testing/index.ts
index d597d47b0188..185d39989c94 100644
--- a/frontend/src/test/insight-testing/index.ts
+++ b/frontend/src/test/insight-testing/index.ts
@@ -26,7 +26,7 @@ export {
series,
sqlChart,
} from './interactions'
-export { personsModal } from './elements'
+export { annotationBadges, personsModal } from './elements'
export { buildActorsResponse, setupInsightMocks } from './mocks'
export type { MockResponse, QueryBody, SetupMocksOptions } from './mocks'
export { expectNoNaN } from './query-helpers'
diff --git a/frontend/src/test/insight-testing/interactions.ts b/frontend/src/test/insight-testing/interactions.ts
index b825c6f8a8e4..feb6fdb0394d 100644
--- a/frontend/src/test/insight-testing/interactions.ts
+++ b/frontend/src/test/insight-testing/interactions.ts
@@ -1,7 +1,8 @@
-import { fireEvent, screen, waitFor, within } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
+ createDefaultTooltipAccessor,
type DefaultTooltipAccessor,
findChart,
getChartTooltip,
@@ -21,16 +22,6 @@ import { type InsightTooltipAccessor, createInsightTooltipAccessor } from './too
const DEBOUNCE_TIMEOUT = 3000
-/* Budget for one chart interaction, shared between its two waits (canvas render, then
- * tooltip poll) rather than given to each in full. Two full DEBOUNCE_TIMEOUTs chained
- * together outlast Jest's 5s per-test budget, so on a loaded shard the test dies before
- * either wait reaches its own deadline, reporting "Exceeded timeout of 5000 ms" against
- * the `it(` line instead of naming the phase that never completed. */
-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())
-
function getLogic(): ReturnType<typeof insightVizDataLogic.build> {
const props: InsightLogicProps = { dashboardItemId: INSIGHT_TEST_ID }
return insightVizDataLogic(props)
@@ -153,26 +144,16 @@ export const chart = {
/** Current chart tooltip element, or null if none is rendered. */
getTooltip: getChartTooltip,
async hoverTooltip(index: number): Promise<InsightTooltipAccessor> {
- const deadline = Date.now() + CHART_INTERACTION_TIMEOUT
- const chart = await findChart({ timeout: budgetUntil(deadline) })
- const tooltip = await chart.hoverTooltip(index, budgetUntil(deadline))
+ const tooltip = await (await findChart()).hoverTooltip(index)
return createInsightTooltipAccessor(tooltip.element)
},
async clickAtIndex(index: number): Promise<void> {
- const deadline = Date.now() + CHART_INTERACTION_TIMEOUT
- const chart = await findChart({ timeout: budgetUntil(deadline) })
- await chart.clickAtIndex(index, budgetUntil(deadline))
+ await (await findChart()).clickAtIndex(index)
},
/** Click a row inside the pinned tooltip by matching its label text. Use
* after `clickAtIndex` has pinned a multi-series tooltip. */
- async clickTooltipRow(label: string | RegExp): Promise<void> {
- const tooltip = await waitForChartTooltip()
- // Each quill tooltip row renders its label twice — a visible copy plus an aria-hidden
- // measurement copy used for truncation layout — so match only the visible one.
- const matches = within(tooltip).getAllByText(label)
- const row = matches.find((el) => !el.closest('[aria-hidden="true"]')) ?? matches[0]
- const clickable = row.closest('[data-attr="hog-chart-tooltip-row"]') ?? row.closest('tr') ?? row
- fireEvent.click(clickable)
+ async clickTooltipRow(label: string): Promise<void> {
+ createDefaultTooltipAccessor(await waitForChartTooltip()).clickRow(label)
},
}
@@ -180,8 +161,6 @@ export const chart = {
* instead of the InsightTooltip table. */
export const sqlChart = {
async hoverTooltip(index: number): Promise<DefaultTooltipAccessor> {
- const deadline = Date.now() + CHART_INTERACTION_TIMEOUT
- const chart = await findChart({ timeout: budgetUntil(deadline) })
- return await chart.hoverTooltip(index, budgetUntil(deadline))
+ return await (await findChart()).hoverTooltip(index)
},
}
diff --git a/packages/quill/packages/charts/package.json b/packages/quill/packages/charts/package.json
index 09cd57e7c512..cc5f847a206d 100644
--- a/packages/quill/packages/charts/package.json
+++ b/packages/quill/packages/charts/package.json
@@ -23,6 +23,12 @@
"require": "./dist/index.cjs",
"default": "./dist/index.js"
},
+ "./testing": {
+ "types": "./dist/testing/index.d.ts",
+ "import": "./dist/testing.js",
+ "require": "./dist/testing.cjs",
+ "default": "./dist/testing.js"
+ },
"./package.json": "./package.json"
},
"publishConfig": {
@@ -59,7 +65,13 @@
"vite-plugin-dts": "^4.5.4"
},
"peerDependencies": {
+ "@testing-library/react": ">=14.3.1",
"react": "^18.3.1 || ^19.0.0",
"react-dom": "^18.3.1 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@testing-library/react": {
+ "optional": true
+ }
}
}
diff --git a/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx b/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx
index a2131aa28d24..c04159e1e6c2 100644
--- a/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/PieChart/PieChart.test.tsx
@@ -4,7 +4,7 @@ import React from 'react'
import type { RadialSlicePayload } from '../../core/hooks/useRadialInteraction'
import { RADIAL_MARGINS } from '../../core/RadialChart'
import type { ResolvedSeries, ChartTheme, Series } from '../../core/types'
-import { getChartTooltip, renderChart } from '../../testing'
+import { type ChartAccessor, getChartTooltip, renderChart } from '../../testing'
import { mockRect } from '../../testing/jsdom'
import { computePieLayout } from './computePieLayout'
import type { PieLayout } from './computePieLayout'
@@ -43,12 +43,6 @@ function pointInSlice(layout: PieLayout, sliceIndex: number): { clientX: number;
}
}
-function sliceLabels(wrapper: HTMLElement): string[] {
- return Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-pie-slice-label"]')).map(
- (el) => el.textContent ?? ''
- )
-}
-
describe('PieChart', () => {
it('renders a canvas labeled as a pie chart with one slice per series', () => {
const { container } = renderChart(<PieChart series={SERIES} theme={THEME} />)
@@ -63,20 +57,23 @@ describe('PieChart', () => {
it('renders one on-slice value label per slice by default', () => {
const { chart } = renderChart(<PieChart series={SERIES} theme={THEME} />)
- const labels = sliceLabels(chart.element)
+ const labels = chart.pie.sliceLabels().map((l) => l.text)
expect(labels).toHaveLength(2)
expect(labels.join('|')).toContain('50')
})
it('renders percentage labels when isPercent is set', () => {
const { chart } = renderChart(<PieChart series={SERIES} theme={THEME} config={{ isPercent: true }} />)
- const text = sliceLabels(chart.element).join('|')
+ const text = chart.pie
+ .sliceLabels()
+ .map((l) => l.text)
+ .join('|')
expect(text).toContain('50%')
})
it('renders value and percentage on one line when sliceValueDisplay is both', () => {
const { chart } = renderChart(<PieChart series={SERIES} theme={THEME} config={{ sliceValueDisplay: 'both' }} />)
- expect(sliceLabels(chart.element).join('|')).toContain('50 (50%)')
+ expect(chart.pie.sliceLabels()[0].lines).toEqual(['50 (50%)'])
})
it.each([
@@ -85,7 +82,7 @@ describe('PieChart', () => {
['shown on a donut that sets showValueOnSlice', { innerRadiusRatio: 0.5, showValueOnSlice: true }, true],
])('on-slice value labels are %s', (_name, config, shown) => {
const { chart } = renderChart(<PieChart series={SERIES} theme={THEME} config={config} />)
- expect(sliceLabels(chart.element).length > 0).toBe(shown)
+ expect(chart.pie.sliceLabels().length > 0).toBe(shown)
})
it('renders a center label for a donut', () => {
@@ -106,7 +103,7 @@ describe('PieChart', () => {
it('renders an empty pie (zero total) without crashing and with no slice labels', () => {
const { chart } = renderChart(<PieChart series={[{ key: 'a', label: 'A', data: [0] }]} theme={THEME} />)
- expect(sliceLabels(chart.element)).toHaveLength(0)
+ expect(chart.pie.sliceLabels()).toHaveLength(0)
})
describe('hover & tooltip', () => {
@@ -210,35 +207,33 @@ describe('PieChart', () => {
})
describe('interactive legend', () => {
- function legendButtons(container: HTMLElement): HTMLButtonElement[] {
- return Array.from(
- container.querySelectorAll<HTMLButtonElement>('[data-attr="hog-chart-pie-legend"] button')
- )
+ function legendButtons(chart: ChartAccessor): HTMLButtonElement[] {
+ return Array.from(chart.legend()?.querySelectorAll('button') ?? [])
}
it('renders no legend by default', () => {
- const { container } = renderChart(<PieChart series={SERIES} theme={THEME} />)
- expect(container.querySelector('[data-attr="hog-chart-pie-legend"]')).toBeNull()
+ const { chart } = renderChart(<PieChart series={SERIES} theme={THEME} />)
+ expect(chart.legend()).toBeNull()
})
it('isolates a slice on legend click and restores them all on a second click', () => {
- const { container } = renderChart(
+ const { chart, container } = renderChart(
<PieChart series={SERIES} theme={THEME} config={{ legend: { show: true } }} />
)
- expect(legendButtons(container).map((b) => b.textContent)).toEqual(['Chrome', 'Firefox'])
+ expect(legendButtons(chart).map((b) => b.textContent)).toEqual(['Chrome', 'Firefox'])
expect(container.querySelector('canvas[aria-label]')?.getAttribute('aria-label')).toBe(
'Pie chart with 2 slices'
)
- fireEvent.click(legendButtons(container)[1])
+ fireEvent.click(legendButtons(chart)[1])
expect(container.querySelector('canvas[aria-label]')?.getAttribute('aria-label')).toBe(
'Pie chart with 1 slices'
)
// The isolated-away row stays in the legend (dimmed) so it can be restored.
- const dimmed = legendButtons(container).filter((b) => b.className.includes('opacity-40'))
+ const dimmed = legendButtons(chart).filter((b) => b.className.includes('opacity-40'))
expect(dimmed.map((b) => b.textContent)).toEqual(['Chrome'])
- fireEvent.click(legendButtons(container)[1])
+ fireEvent.click(legendButtons(chart)[1])
expect(container.querySelector('canvas[aria-label]')?.getAttribute('aria-label')).toBe(
'Pie chart with 2 slices'
)
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 b81a20b564fe..d065d2334e25 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
@@ -47,8 +47,8 @@ describe('SankeyChart', () => {
config={{ columnLabels: ['Init', '1st tool', 'Outcome', 'unused'], showNodeValues: true }}
/>
)
- expect(chart.sankeyNodeLabels()).toEqual(['Start 12', 'Tool A 12', 'Completed 12'])
- expect(chart.sankeyColumnLabels()).toEqual(['Init', '1st tool', 'Outcome'])
+ expect(chart.sankey.nodeLabels()).toEqual(['Start 12', 'Tool A 12', 'Completed 12'])
+ expect(chart.sankey.columnLabels()).toEqual(['Init', '1st tool', 'Outcome'])
expect(chart.canvas.getAttribute('aria-label')).toBe('Sankey chart with 3 nodes and 2 links')
})
@@ -72,7 +72,7 @@ describe('SankeyChart', () => {
config={{ nodePadding: 0 }}
/>
)
- expect(chart.sankeyNodeLabels()).toEqual(['Start', 'Big', 'Thin'])
+ expect(chart.sankey.nodeLabels()).toEqual(['Start', 'Big', 'Thin'])
})
it('shows the hovered node in the tooltip, reports it once, and fires onNodeClick for it', async () => {
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
index 0071be0cd499..38c4cea3b186 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
@@ -30,7 +30,7 @@ describe('SlopeChart', () => {
it('renders empty state without crashing', () => {
const { chart } = renderChart(<SlopeChart series={[]} labels={LABELS} theme={THEME} />)
expect(chart.seriesCount).toBe(0)
- expect(chart.slopeValueLabels()).toHaveLength(0)
+ expect(chart.slope.valueLabels()).toHaveLength(0)
})
it('skips excluded series everywhere', () => {
@@ -47,14 +47,14 @@ describe('SlopeChart', () => {
<SlopeChart series={series} labels={LABELS} config={{ legend: { show: true } }} theme={THEME} />
)
expect(chart.seriesCount).toBe(2)
- expect(chart.slopeSeriesLabels()).not.toContain('C')
+ expect(chart.slope.seriesLabels()).not.toContain('C')
expect(chart.legendItems().map((i) => i.label)).not.toContain('C')
})
describe('value labels', () => {
it('shows both start and end value labels for every series by default', () => {
const { chart } = renderChart(<SlopeChart series={SERIES} labels={LABELS} theme={THEME} />)
- const labels = chart.slopeValueLabels()
+ const labels = chart.slope.valueLabels()
expect(
labels
.filter((l) => l.side === 'start')
@@ -83,7 +83,7 @@ describe('SlopeChart', () => {
{ key: 'b', label: 'B', data: [80, 20] },
]
const { chart } = renderChart(<SlopeChart series={series} labels={LABELS} theme={THEME} config={config} />)
- const sideTexts = chart.slopeValueLabels().filter((l) => l.side === side)
+ const sideTexts = chart.slope.valueLabels().filter((l) => l.side === side)
// The toggled series (`a`) is missing from that column, the other (`b`) remains.
const aValue = side === 'start' ? '10' : '90'
expect(sideTexts.map((l) => l.text)).not.toContain(aValue)
@@ -101,7 +101,7 @@ describe('SlopeChart', () => {
{ key: 'b', label: 'B', data: [80, 20] },
]
const { chart } = renderChart(<SlopeChart series={series} labels={LABELS} theme={THEME} />)
- const texts = chart.slopeValueLabels().map((l) => l.text)
+ const texts = chart.slope.valueLabels().map((l) => l.text)
expect(texts).toEqual(expect.arrayContaining(['80', '20']))
expect(texts).not.toContain('10')
expect(texts).not.toContain('90')
@@ -111,7 +111,7 @@ describe('SlopeChart', () => {
const { chart } = renderChart(
<SlopeChart series={SERIES} labels={LABELS} config={{ valueFormatter: (v) => `${v}%` }} theme={THEME} />
)
- expect(chart.slopeValueLabels().every((l) => l.text.endsWith('%'))).toBe(true)
+ expect(chart.slope.valueLabels().every((l) => l.text.endsWith('%'))).toBe(true)
})
it('keeps the computed label gutter when a margins override side is undefined', () => {
@@ -133,14 +133,14 @@ describe('SlopeChart', () => {
describe('series labels', () => {
it('renders a name label per series by default', () => {
const { chart } = renderChart(<SlopeChart series={SERIES} labels={LABELS} theme={THEME} />)
- expect(chart.slopeSeriesLabels().sort()).toEqual(['A', 'B'])
+ expect(chart.slope.seriesLabels().sort()).toEqual(['A', 'B'])
})
it('hides all name labels when showSeriesLabels is false', () => {
const { chart } = renderChart(
<SlopeChart series={SERIES} labels={LABELS} config={{ showSeriesLabels: false }} theme={THEME} />
)
- expect(chart.slopeSeriesLabels()).toHaveLength(0)
+ expect(chart.slope.seriesLabels()).toHaveLength(0)
})
it('keeps the highest-change name and drops a colliding low-change one', () => {
@@ -150,7 +150,7 @@ describe('SlopeChart', () => {
{ key: 'sml', label: 'Small', data: [98, 100] },
]
const { chart } = renderChart(<SlopeChart series={series} labels={LABELS} theme={THEME} />)
- expect(chart.slopeSeriesLabels()).toEqual(['Big'])
+ expect(chart.slope.seriesLabels()).toEqual(['Big'])
})
})
@@ -287,7 +287,7 @@ describe('SlopeChart', () => {
],
])('%s: value labels read the true start and end values', (_desc, series, expected) => {
const { chart } = renderChart(<SlopeChart series={series} labels={LABELS} theme={THEME} />)
- const labels = chart.slopeValueLabels().map((l) => ({ side: l.side, text: l.text }))
+ const labels = chart.slope.valueLabels().map((l) => ({ side: l.side, text: l.text }))
for (const e of expected) {
expect(labels).toContainEqual(e)
}
@@ -301,7 +301,7 @@ describe('SlopeChart', () => {
const { chart } = renderChart(<SlopeChart series={series} labels={labels} theme={THEME} />)
// Only the two ends are shown — interior points and labels are dropped.
expect(chart.xTicks()).toEqual(['Jan', 'Apr'])
- const values = chart.slopeValueLabels().map((l) => ({ side: l.side, text: l.text }))
+ const values = chart.slope.valueLabels().map((l) => ({ side: l.side, text: l.text }))
expect(values).toContainEqual({ side: 'start', text: '10' })
expect(values).toContainEqual({ side: 'end', text: '40' })
})
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx
index 6bfd78d1fd2e..d6501ae96613 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx
+++ b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.test.tsx
@@ -89,7 +89,7 @@ describe('useChartCanvas', () => {
const canvas = renderCanvas(drawStatic)
drawStatic.mockClear()
- jest.mocked(Element.prototype.getBoundingClientRect).mockReturnValueOnce({ ...mockRect, width: 0, height: 0 })
+ jest.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValueOnce({ ...mockRect, width: 0, height: 0 })
act(() => {
canvas.dispatchEvent(new Event('contextrestored'))
})
diff --git a/packages/quill/packages/charts/src/docs/TESTING.md b/packages/quill/packages/charts/src/docs/TESTING.md
index afddf6f3af38..16c2d9774143 100644
--- a/packages/quill/packages/charts/src/docs/TESTING.md
+++ b/packages/quill/packages/charts/src/docs/TESTING.md
@@ -29,9 +29,10 @@ it('renders the goal line on the dashboard chart', async () => {
})
```
+- Outside this repo, install `@testing-library/react` next to `@posthog/quill-charts`. The helpers need a jsdom test environment and a runner with global `beforeEach` and `afterEach`.
- `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`.
+- `chart.hoverTooltip(i)` hovers the label at index `i` until the tooltip shows its content, then reads it as a `DefaultTooltip`. `tooltip.clickRow('Pageviews')` clicks a row. For a custom tooltip, read `tooltip.element`.
The accessor surface (full list in `testing/accessor.ts`):
@@ -50,11 +51,14 @@ chart.hasRightAxis // boolean
chart.referenceLines() // [{ label, position, color, orientation }, …]
chart.valueLabels() // [{ text, color }, …]
chart.anomalyPoints() // [{ element, color }, …] (TimeSeriesLineChart)
-chart.annotationBadges() // HTMLElement[]
+chart.legend() // legend container in the render scope, null when hidden
chart.legendItems() // [{ label, secondaryLabel }, …] legend rows in the render scope, empty when hidden
chart.clickLegendItem('A', { additive: true }) // click a legend row, additive toggles instead of isolating
-chart.sankeyNodeLabels() // ['/home', '/pricing', …] Sankey node labels in layout order, after overlap hiding
-chart.sankeyColumnLabels() // ['Step 1', 'Step 2', …] Sankey column headers, left to right
+chart.slope.valueLabels() // [{ text, color, side }, …] slope value labels, start and end columns
+chart.slope.seriesLabels() // slope series names, after collision avoidance
+chart.sankey.nodeLabels() // ['/home', '/pricing', …] Sankey node labels in layout order, after overlap hiding
+chart.sankey.columnLabels() // ['Step 1', 'Step 2', …] Sankey column headers, left to right
+chart.pie.sliceLabels() // [{ text, lines }, …] on-slice labels, one entry per slice
```
Gestures work under any wrapper, because the chart records its label count on its root:
diff --git a/packages/quill/packages/charts/src/docs/tooltips.md b/packages/quill/packages/charts/src/docs/tooltips.md
index e868bda04d73..7922c9f7cbae 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), `await chart.hoverTooltip(i)` 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()`, `clickRow(seriesLabel)`.
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/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.ts
index a7d6cfe96bc4..0754b49a780d 100644
--- a/packages/quill/packages/charts/src/testing/accessor.ts
+++ b/packages/quill/packages/charts/src/testing/accessor.ts
@@ -58,6 +58,12 @@ interface SlopeValueLabelSummary {
side: 'start' | 'end'
}
+interface PieSliceLabelSummary {
+ text: string
+ /** One entry per rendered line (label and/or value). */
+ lines: string[]
+}
+
interface LegendItemSummary {
label: string
/** The row's secondary text (a slope chart's change, a proportion bar's `share · value`), or null
@@ -90,25 +96,31 @@ export interface ChartAccessor<Meta = unknown> {
valueLabels(): ValueLabelSummary[]
/** All anomaly point markers currently rendered (TimeSeriesLineChart only). */
anomalyPoints(): AnomalyPointSummary[]
- /** All slope-chart value labels currently rendered (start + end columns). */
- slopeValueLabels(): SlopeValueLabelSummary[]
- /** Series name labels currently rendered by a slope chart (post-collision-avoidance). */
- slopeSeriesLabels(): string[]
+ slope: {
+ /** Value labels currently rendered (start + end columns). */
+ valueLabels(): SlopeValueLabelSummary[]
+ /** Series name labels currently rendered (post-collision-avoidance). */
+ seriesLabels(): string[]
+ }
+ sankey: {
+ /** Node labels in layout order. */
+ nodeLabels(): string[]
+ /** Column headers, left to right. */
+ columnLabels(): string[]
+ }
+ pie: {
+ /** On-slice labels, in slice order. */
+ sliceLabels(): PieSliceLabelSummary[]
+ }
+ /** The legend container in this chart's render scope, or null when the legend is hidden. */
+ legend(): HTMLElement | null
/** Legend rows in this chart's render scope — label plus the row's secondary text (a slope
* chart's change, a proportion bar's `share · value`), or null when none. Empty when the
* legend is hidden. */
legendItems(): LegendItemSummary[]
- /** @deprecated Use `legendItems()`, which reads any chart's legend. */
- slopeLegendItems(): LegendItemSummary[]
/** Click the legend row with this label. `additive` holds ⌘/Ctrl, which toggles that one series
* instead of isolating it. Throws when no legend row has the label. */
clickLegendItem(label: string, options?: { additive?: boolean }): void
- /** Node labels rendered by a Sankey chart, in layout order. */
- sankeyNodeLabels(): string[]
- /** Column headers rendered by a Sankey chart, left to right. */
- sankeyColumnLabels(): string[]
- /** Annotation badges currently rendered. */
- annotationBadges(): HTMLElement[]
/** 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`.
@@ -259,20 +271,32 @@ export function getChart<Meta = unknown>(
element: el,
color: el.style.backgroundColor,
})),
- slopeValueLabels: () =>
- Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-slope-value-label"]')).map(
- (el) => ({
- text: el.textContent ?? '',
- color: el.style.color,
- side: el.dataset.slopeSide === 'end' ? 'end' : 'start',
- })
- ),
- slopeSeriesLabels: () =>
- Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-slope-series-label"]')).map(
- (el) => el.textContent ?? ''
- ),
+ slope: {
+ valueLabels: () =>
+ Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-slope-value-label"]')).map(
+ (el) => ({
+ text: el.textContent ?? '',
+ color: el.style.color,
+ side: el.dataset.slopeSide === 'end' ? 'end' : 'start',
+ })
+ ),
+ seriesLabels: () => textsOf(wrapper, 'hog-chart-slope-series-label'),
+ },
+ sankey: {
+ nodeLabels: () => textsOf(wrapper, 'hog-chart-sankey-node-label'),
+ columnLabels: () => textsOf(wrapper, 'hog-chart-sankey-column-label'),
+ },
+ pie: {
+ sliceLabels: () =>
+ Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-pie-slice-label"]')).map(
+ (el) => ({
+ text: el.textContent ?? '',
+ lines: Array.from(el.querySelectorAll('div')).map((line) => line.textContent ?? ''),
+ })
+ ),
+ },
+ legend: () => scope.querySelector<HTMLElement>('[data-hog-charts-legend]'),
legendItems: () => readLegendItems(scope),
- slopeLegendItems: () => readLegendItems(scope),
clickLegendItem(label: string, { additive = false }: { additive?: boolean } = {}): void {
const labelEl = Array.from(
scope.querySelectorAll<HTMLElement>('[data-attr="hog-chart-legend-label"]')
@@ -285,15 +309,6 @@ export function getChart<Meta = unknown>(
fireEvent.click(row, { metaKey: additive })
})
},
- sankeyNodeLabels: () =>
- Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-sankey-node-label"]')).map(
- (el) => el.textContent ?? ''
- ),
- sankeyColumnLabels: () =>
- Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-sankey-column-label"]')).map(
- (el) => el.textContent ?? ''
- ),
- annotationBadges: () => Array.from(wrapper.querySelectorAll<HTMLElement>('.AnnotationsBadge')),
hoverAtIndex(index: number): void {
hoverAtIndex(wrapper, index, labelCount())
},
@@ -334,6 +349,10 @@ export function getChart<Meta = unknown>(
}
}
+function textsOf(root: ParentNode, dataAttr: string): string[] {
+ return Array.from(root.querySelectorAll<HTMLElement>(`[data-attr="${dataAttr}"]`)).map((el) => el.textContent ?? '')
+}
+
// The legend renders as a sibling of the chart wrapper (inside ChartLegendLayout), so it lives in the
// broader render scope rather than under the chart wrapper.
function readLegendItems(scope: ParentNode): LegendItemSummary[] {
diff --git a/packages/quill/packages/charts/src/testing/jsdom.ts b/packages/quill/packages/charts/src/testing/jsdom.ts
index b0e7c86dab07..b6c302f32609 100644
--- a/packages/quill/packages/charts/src/testing/jsdom.ts
+++ b/packages/quill/packages/charts/src/testing/jsdom.ts
@@ -43,8 +43,12 @@ export function setupJsdom(): () => void {
disconnect(): void {}
} as unknown as typeof ResizeObserver
}
- const spy = jest.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue(mockRect)
- return () => spy.mockRestore()
+ // Not `jest.spyOn`, so the helpers also run under other test runners.
+ const original = Element.prototype.getBoundingClientRect
+ Element.prototype.getBoundingClientRect = () => mockRect
+ return () => {
+ Element.prototype.getBoundingClientRect = original
+ }
}
/** Run requestAnimationFrame callbacks synchronously for the duration of a
diff --git a/packages/quill/packages/charts/src/testing/tooltip.ts b/packages/quill/packages/charts/src/testing/tooltip.ts
index a5b9dd0a7c0e..10eec6791368 100644
--- a/packages/quill/packages/charts/src/testing/tooltip.ts
+++ b/packages/quill/packages/charts/src/testing/tooltip.ts
@@ -1,4 +1,4 @@
-import { waitFor } from '@testing-library/react'
+import { act, fireEvent, waitFor } from '@testing-library/react'
/** Stable selector for the chart tooltip portal — quill-charts renders this on
* the document root via FloatingPortal, so it can't be found inside the chart
@@ -38,6 +38,8 @@ export interface DefaultTooltipAccessor extends ChartTooltipAccessor {
swatchColors(): string[]
/** Formatted total-row value, or undefined when no total row is shown. */
total(): string | undefined
+ /** Click the series row with this label. Throws when no row has the label. */
+ clickRow(seriesLabel: string): void
}
const seriesLabelOf = (row: HTMLElement): string =>
@@ -68,6 +70,15 @@ export function createDefaultTooltipAccessor(element: HTMLElement): DefaultToolt
const total = element.querySelector('[data-attr="hog-chart-tooltip-total"]')
return total?.querySelector('[data-attr="hog-chart-tooltip-value"]')?.textContent ?? undefined
},
+ clickRow(seriesLabel: string): void {
+ const row = rowEls().find((r) => seriesLabelOf(r) === seriesLabel)
+ if (!row) {
+ throw new Error(`No tooltip row labelled "${seriesLabel}"`)
+ }
+ act(() => {
+ fireEvent.click(row)
+ })
+ },
})
}
diff --git a/packages/quill/packages/charts/tsconfig.build.json b/packages/quill/packages/charts/tsconfig.build.json
index f92e1c90d951..6537c54398b5 100644
--- a/packages/quill/packages/charts/tsconfig.build.json
+++ b/packages/quill/packages/charts/tsconfig.build.json
@@ -10,7 +10,6 @@
"src/**/*.test.tsx",
"src/**/*.stories.ts",
"src/**/*.stories.tsx",
- "src/testing",
"src/story-helpers.tsx"
]
}
diff --git a/packages/quill/packages/charts/vite.config.ts b/packages/quill/packages/charts/vite.config.ts
index 9c94c014beeb..0662dd097dab 100644
--- a/packages/quill/packages/charts/vite.config.ts
+++ b/packages/quill/packages/charts/vite.config.ts
@@ -8,9 +8,9 @@ import dts from 'vite-plugin-dts'
* pipeline. The runtime deps (d3-*, dayjs, @floating-ui/react,
* simple-statistics) stay external and are redeclared as real
* `dependencies` so the consumer's package manager installs them; react /
- * react-dom are peers. The dev/story-only entries (testing, story-helpers)
- * are excluded — in-repo consumers reach them via tsconfig path aliases /
- * jest moduleNameMapper against src, not the published package.
+ * react-dom are peers. `testing` ships as a second entry so code outside
+ * this repo can test its charts; @testing-library/react is an optional peer.
+ * story-helpers stays unpublished — only this repo's stories use it.
*/
export default defineConfig({
plugins: [
@@ -22,16 +22,18 @@ export default defineConfig({
'src/**/*.test.tsx',
'src/**/*.stories.ts',
'src/**/*.stories.tsx',
- 'src/testing/**',
'src/story-helpers.tsx',
],
}),
],
build: {
lib: {
- entry: resolve(__dirname, 'src/index.ts'),
+ entry: {
+ index: resolve(__dirname, 'src/index.ts'),
+ testing: resolve(__dirname, 'src/testing/index.ts'),
+ },
formats: ['es', 'cjs'],
- fileName: (format) => `index.${format === 'es' ? 'js' : 'cjs'}`,
+ fileName: (format, entryName) => `${entryName}.${format === 'es' ? 'js' : 'cjs'}`,
},
rollupOptions: {
external: [
@@ -39,6 +41,7 @@ export default defineConfig({
'react-dom',
'react/jsx-runtime',
'@floating-ui/react',
+ '@testing-library/react',
'd3-array',
'd3-color',
'd3-scale',
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
index 519fe63f4cb2..89c10da894c5 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
@@ -6,7 +6,14 @@ import { dimensions, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/test
import { ExportType } from '~/exporter/types'
import { NodeKind } from '~/queries/schema/schema-general'
-import { buildTrendsQuery, chart, getChart, personsModal, renderInsight } from '~/test/insight-testing'
+import {
+ annotationBadges,
+ buildTrendsQuery,
+ chart,
+ getChart,
+ personsModal,
+ renderInsight,
+} from '~/test/insight-testing'
import { buildAnnotation } from '~/test/insight-testing/test-data'
import { AnnotationScope, ChartDisplayType } from '~/types'
@@ -554,7 +561,7 @@ describe('TrendsBarChart overlays', () => {
await screen.findByLabelText(/chart with/i, undefined, { timeout: 5000 })
await waitFor(
() => {
- expect(getChart().annotationBadges().length).toBeGreaterThan(0)
+ expect(annotationBadges().length).toBeGreaterThan(0)
},
{ timeout: 5000 }
)
diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx
index 2cd5352b7aed..9d8a8e4f66bf 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx
@@ -5,7 +5,7 @@ import { cleanup, screen, waitFor } from '@testing-library/react'
import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
import { NodeKind } from '~/queries/schema/schema-general'
-import { buildTrendsQuery, legend, personsModal, renderInsight } from '~/test/insight-testing'
+import { buildTrendsQuery, getChart, legend, personsModal, renderInsight } from '~/test/insight-testing'
import { ChartDisplayType } from '~/types'
let cleanupJsdom: () => void
@@ -24,9 +24,9 @@ afterEach(() => {
})
function sliceLabels(): string[] {
- return Array.from(document.querySelectorAll('[data-attr="hog-chart-pie-slice-label"]')).map(
- (el) => el.textContent ?? ''
- )
+ return getChart()
+ .pie.sliceLabels()
+ .map((label) => label.text)
}
// Napped × hedgehog fixture: Spike 11, Thistle 4, Bramble 2, Prickles 2, Conker 0.
@@ -91,21 +91,18 @@ describe('TrendsPieChart', () => {
})
describe('quill in-chart legend', () => {
- const getInChartLegend = (container: HTMLElement): HTMLElement | null =>
- container.querySelector<HTMLElement>('[data-attr="hog-chart-pie-legend"]')
-
it('renders the in-chart legend and suppresses the legacy side legend', async () => {
const { container } = renderInsight({ query: pieByHedgehog({ showLegend: true }) })
await screen.findByLabelText(/pie chart with/i, undefined, { timeout: 5000 })
- const legendEl = getInChartLegend(container)
+ const legendEl = getChart().legend()
expect(legendEl).not.toBeNull()
expect(legendEl!.textContent).toContain('Spike')
expect(container.querySelector('.InsightLegendMenu')).not.toBeInTheDocument()
})
it('humanizes built-in event names in the legend (no breakdown)', async () => {
- const { container } = renderInsight({
+ renderInsight({
query: buildTrendsQuery({
series: [{ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }],
trendsFilter: { display: ChartDisplayType.ActionsPie, showLegend: true },
@@ -113,14 +110,14 @@ describe('TrendsPieChart', () => {
})
await screen.findByLabelText(/pie chart with/i, undefined, { timeout: 5000 })
- const legendEl = getInChartLegend(container)
+ const legendEl = getChart().legend()
expect(legendEl).not.toBeNull()
expect(legendEl!.textContent).toContain('Pageview')
expect(legendEl!.textContent).not.toContain('$pageview')
})
it('removes a toggled-off slice but keeps it listed (dimmed) so it can be restored', async () => {
- const { container } = renderInsight({ query: pieByHedgehog({ showLegend: true }) })
+ renderInsight({ query: pieByHedgehog({ showLegend: true }) })
await screen.findByLabelText(/pie chart with 5 slices/i, undefined, { timeout: 5000 })
await legend.toggle('Spike')
@@ -128,7 +125,7 @@ describe('TrendsPieChart', () => {
await waitFor(() => {
expect(screen.getByLabelText(/pie chart with 4 slices/i)).toBeInTheDocument()
})
- const dimmed = [...getInChartLegend(container)!.querySelectorAll<HTMLElement>('button')].filter((b) =>
+ const dimmed = [...getChart().legend()!.querySelectorAll<HTMLElement>('button')].filter((b) =>
b.className.includes('opacity-40')
)
expect(dimmed.map((b) => b.textContent)).toEqual(['Spike'])