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.

refactor(hog-charts): richer test API + registry-based capture (#57946)

Sam Penningtonc056cf10ba87
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
index 6526a0e452e3..d1a772012506 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
@@ -1,8 +1,8 @@
-import { cleanup, waitFor } from '@testing-library/react'
+import { waitFor } from '@testing-library/react'
import type { BarChartConfig, ChartTheme, Series } from '../../core/types'
import { ReferenceLine } from '../../overlays/ReferenceLine'
-import { clickAtIndex, hoverAtIndex, renderHogChart, setupJsdom, setupSyncRaf } from '../../testing'
+import { renderHogChart } from '../../testing'
import { BarChart } from './BarChart'
const THEME: ChartTheme = {
@@ -23,20 +23,6 @@ type Layout = 'stacked' | 'grouped' | 'percent'
type Orientation = 'vertical' | 'horizontal'
describe('BarChart', () => {
- let teardownJsdom: () => void
- let teardownRaf: () => void
-
- beforeEach(() => {
- teardownJsdom = setupJsdom()
- teardownRaf = setupSyncRaf()
- })
-
- afterEach(() => {
- teardownRaf()
- teardownJsdom()
- cleanup()
- })
-
describe.each<[Layout, Orientation]>([
['stacked', 'vertical'],
['grouped', 'vertical'],
@@ -158,7 +144,7 @@ describe('BarChart', () => {
describe('hover & tooltip', () => {
it('mounts a tooltip on hover', async () => {
const { chart } = renderHogChart(<BarChart series={SERIES} labels={LABELS} theme={THEME} />)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
const tooltip = await chart.waitForTooltip()
expect(tooltip.element.textContent).toContain('Tue')
})
@@ -168,7 +154,7 @@ describe('BarChart', () => {
const { chart } = renderHogChart(
<BarChart series={SERIES} labels={LABELS} theme={THEME} onPointClick={onPointClick} />
)
- await clickAtIndex(chart.element, 1, LABELS.length)
+ await chart.clickAtIndex(1)
expect(onPointClick).toHaveBeenCalledWith(expect.objectContaining({ dataIndex: 1, label: 'Tue' }))
})
@@ -186,7 +172,7 @@ describe('BarChart', () => {
},
])('$name', async ({ config, expectedKeys }) => {
const { chart } = renderHogChart(<BarChart series={SERIES} labels={LABELS} theme={THEME} config={config} />)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
const tooltip = await chart.waitForTooltip()
expect(tooltip.seriesData.map((s) => s.series.key)).toEqual(expectedKeys)
})
@@ -195,11 +181,9 @@ describe('BarChart', () => {
const { chart } = renderHogChart(
<BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ tooltip: { pinnable: true } }} />
)
- hoverAtIndex(chart.element, 1, LABELS.length)
- await chart.waitForTooltip()
- await clickAtIndex(chart.element, 1, LABELS.length)
+ await chart.clickAtIndex(1)
const tooltip = await chart.waitForTooltip()
- expect(tooltip.element.classList.contains('hog-charts-tooltip--pinned')).toBe(true)
+ expect(tooltip.isPinned).toBe(true)
})
it('omits a series from tooltip when visibility.tooltip is false', async () => {
@@ -208,7 +192,7 @@ describe('BarChart', () => {
{ key: 'b', label: 'B', data: [5, 15, 25], visibility: { tooltip: false } },
]
const { chart } = renderHogChart(<BarChart series={series} labels={LABELS} theme={THEME} />)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
const tooltip = await chart.waitForTooltip()
expect(tooltip.element.textContent).toContain('A')
expect(tooltip.element.textContent).not.toContain('B')
@@ -247,7 +231,7 @@ describe('BarChart', () => {
const { chart } = renderHogChart(
<BarChart series={SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} onError={onError} />
)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
await waitFor(() => expect(onError).toHaveBeenCalled())
} finally {
consoleErrorSpy.mockRestore()
diff --git a/frontend/src/lib/hog-charts/charts/LineChart.test.tsx b/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
index 8891eab90835..f3cee5d95ff1 100644
--- a/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
@@ -1,8 +1,6 @@
-import { cleanup } from '@testing-library/react'
-
import type { ChartTheme, Series } from '../core/types'
import { ReferenceLine } from '../overlays/ReferenceLine'
-import { clickAtIndex, hoverAtIndex, renderHogChart, setupJsdom, setupSyncRaf } from '../testing'
+import { renderHogChart } from '../testing'
import { LineChart } from './LineChart'
const THEME: ChartTheme = {
@@ -20,20 +18,6 @@ const SERIES: Series[] = [
const LABELS = ['Mon', 'Tue', 'Wed']
describe('LineChart', () => {
- let teardownJsdom: () => void
- let teardownRaf: () => void
-
- beforeEach(() => {
- teardownJsdom = setupJsdom()
- teardownRaf = setupSyncRaf()
- })
-
- afterEach(() => {
- teardownRaf()
- teardownJsdom()
- cleanup()
- })
-
it.each([
['default config', SERIES, undefined],
['area mode', [{ key: 'a', label: 'A', data: [10, 20, 30], fill: {} }] as Series[], undefined],
@@ -141,7 +125,7 @@ describe('LineChart', () => {
describe('hover & tooltip', () => {
it('mounts a tooltip on hover', async () => {
const { chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
const tooltip = await chart.waitForTooltip()
expect(tooltip.element.textContent).toContain('Tue')
})
@@ -151,7 +135,7 @@ describe('LineChart', () => {
const { chart } = renderHogChart(
<LineChart series={SERIES} labels={LABELS} theme={THEME} onPointClick={onPointClick} />
)
- await clickAtIndex(chart.element, 1, LABELS.length)
+ await chart.clickAtIndex(1)
expect(onPointClick).toHaveBeenCalledWith(
expect.objectContaining({ dataIndex: 1, label: 'Tue', value: 20 })
)
@@ -159,7 +143,7 @@ describe('LineChart', () => {
it('passes hovered seriesData to the tooltip render prop', async () => {
const { chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
const tooltip = await chart.waitForTooltip()
expect(tooltip.seriesData).toHaveLength(SERIES.length)
})
@@ -168,11 +152,9 @@ describe('LineChart', () => {
const { chart } = renderHogChart(
<LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ tooltip: { pinnable: true } }} />
)
- hoverAtIndex(chart.element, 1, LABELS.length)
- await chart.waitForTooltip()
- await clickAtIndex(chart.element, 1, LABELS.length)
+ await chart.clickAtIndex(1)
const tooltip = await chart.waitForTooltip()
- expect(tooltip.element.classList.contains('hog-charts-tooltip--pinned')).toBe(true)
+ expect(tooltip.isPinned).toBe(true)
})
it('does not crash on hover for overlay series', async () => {
@@ -181,7 +163,7 @@ describe('LineChart', () => {
{ key: 'b', label: 'B', data: [5, 15, 25], overlay: true },
]
const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
const tooltip = await chart.waitForTooltip()
expect(tooltip.element.textContent).toContain('Tue')
})
@@ -192,7 +174,7 @@ describe('LineChart', () => {
{ key: 'b', label: 'B', data: [5, 15, 25], visibility: { tooltip: false } },
]
const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
const tooltip = await chart.waitForTooltip()
expect(tooltip.element.textContent).toContain('A')
expect(tooltip.element.textContent).not.toContain('B')
@@ -232,7 +214,7 @@ describe('LineChart', () => {
const { chart } = renderHogChart(
<LineChart series={SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} onError={onError} />
)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
expect(onError).toHaveBeenCalled()
} finally {
consoleErrorSpy.mockRestore()
diff --git a/frontend/src/lib/hog-charts/docs/TESTING.md b/frontend/src/lib/hog-charts/docs/TESTING.md
index 9e707ae4de5d..cb7826d1ccfb 100644
--- a/frontend/src/lib/hog-charts/docs/TESTING.md
+++ b/frontend/src/lib/hog-charts/docs/TESTING.md
@@ -43,29 +43,31 @@ chart.annotationBadges() // HTMLElement[]
Map a label index to canvas coordinates and fire the right event. `clickAtIndex` is hover-then-click — the chart's click handler reads live tooltip context to choose between pinning and `onPointClick`, so a bare `fireEvent.click` without a prior hover takes the wrong branch.
```tsx
-hoverAtIndex(chart.element, 1, LABELS.length) // mouseMove over labels[1]
-await clickAtIndex(chart.element, 1, LABELS.length) // hover then click
+chart.hoverAtIndex(1) // mouseMove over labels[1]
+await chart.clickAtIndex(1) // hover then click
```
+The label count comes from `ui.props.labels`, captured at `renderHogChart` time. Outside `renderHogChart` (e.g. when calling `getHogChart(scope)` on a custom render tree), use the module-level `hoverAtIndex(wrapper, i, totalLabels)` / `clickAtIndex(wrapper, i, totalLabels)` instead.
+
### Tooltip helpers
-The tooltip mounts in a `FloatingPortal` on the document root, so it isn't inside the chart wrapper and can't be reached with `chart.element.querySelector`.
+`chart.waitForTooltip()` resolves once the tooltip mounts and returns a snapshot — the structured `TooltipContext` the chart computed plus the rendered portal element and an `isPinned` flag.
```tsx
-const tooltip = await waitForHogChartTooltip() // resolves once mounted
-expect(tooltip.textContent).toContain('Tue')
-
-const current = getHogChartTooltip() // null if not mounted
-expect(current?.classList.contains('hog-charts-tooltip--pinned')).toBe(true)
+const tooltip = await chart.waitForTooltip()
+expect(tooltip.label).toBe('Tue')
+expect(tooltip.seriesData).toHaveLength(2)
+expect(tooltip.element.textContent).toContain('Tue')
+expect(tooltip.isPinned).toBe(false)
```
+The tooltip mounts in a `FloatingPortal` on the document root, so it isn't inside `chart.element`. Module-level `waitForHogChartTooltip()` / `getHogChartTooltip()` are still exported for cases where you don't have a `chart` accessor handy (e.g. an insight tree behind kea wrappers — see `frontend/src/test/insight-testing/`).
+
## Boilerplate
```tsx
-import { cleanup } from '@testing-library/react'
-
import type { ChartTheme, Series } from '../core/types'
-import { renderHogChart, setupJsdom, setupSyncRaf } from '../testing'
+import { renderHogChart } from '../testing'
import { LineChart } from './LineChart'
const THEME: ChartTheme = { colors: ['#111', '#222'], backgroundColor: '#ffffff' }
@@ -73,19 +75,6 @@ const LABELS = ['Mon', 'Tue', 'Wed']
const SERIES: Series[] = [{ key: 'a', label: 'A', data: [1, 2, 3] }]
describe('LineChart', () => {
- let teardownJsdom: () => void
- let teardownRaf: () => void
-
- beforeEach(() => {
- teardownJsdom = setupJsdom()
- teardownRaf = setupSyncRaf()
- })
- afterEach(() => {
- teardownRaf()
- teardownJsdom()
- cleanup()
- })
-
it('formats percent-stack y-ticks by default', () => {
const { chart } = renderHogChart(
<LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ percentStackView: true }} />
@@ -95,7 +84,7 @@ describe('LineChart', () => {
})
```
-`setupJsdom` mocks `ResizeObserver` and `getBoundingClientRect` so the chart computes real dimensions — without it the chart sees 0×0 and renders nothing measurable. `setupSyncRaf` runs `requestAnimationFrame` synchronously so the static-layer draw commits to the DOM before assertions run; without it the accessor reads stale state and `yTicks()` / `valueLabels()` come back empty.
+`renderHogChart` installs the jsdom mocks (`ResizeObserver`, `getBoundingClientRect`) and a synchronous `requestAnimationFrame` shim on first call — without them the chart sees 0×0 and the static-layer draw doesn't flush before assertions. It also calls `cleanup()` and removes any leftover tooltip portal, so test files don't need a `beforeEach`/`afterEach` for those. Use the explicit `setupJsdom()` / `setupSyncRaf()` only when you need fine-grained teardown control.
## Recipes
@@ -107,35 +96,31 @@ it('pins the tooltip on click when pinnable', async () => {
<LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ tooltip: { pinnable: true } }} />
)
- hoverAtIndex(chart.element, 1, LABELS.length)
- const tooltip = await waitForHogChartTooltip()
- expect(tooltip.textContent).toContain('Tue')
-
- await clickAtIndex(chart.element, 1, LABELS.length)
- expect(getHogChartTooltip()?.classList.contains('hog-charts-tooltip--pinned')).toBe(true)
+ await chart.clickAtIndex(1)
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.isPinned).toBe(true)
})
```
-### Render a custom tooltip
+### Assert against the structured tooltip context
-When a chart is given a `tooltip` render prop, that function receives `TooltipContext`. Trigger it with `hoverAtIndex` and read the rendered output through the tooltip portal.
+The `chart.waitForTooltip()` snapshot includes the same `TooltipContext` the chart's `tooltip` render prop would receive — read `seriesData`, `label`, `dataIndex`, etc. directly without round-tripping through DOM.
```tsx
-it('passes hovered seriesData to a custom tooltip', async () => {
- const tooltip = (ctx: TooltipContext): React.ReactNode => (
- <div data-attr="custom-tooltip">{ctx.seriesData.map((s) => s.value).join(',')}</div>
- )
- const { chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} />)
+it('passes hovered seriesData to the tooltip', async () => {
+ const { chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)
- hoverAtIndex(chart.element, 1, LABELS.length)
- const node = await waitForHogChartTooltip()
- expect(node.querySelector('[data-attr="custom-tooltip"]')?.textContent).toBe('2')
+ chart.hoverAtIndex(1)
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.seriesData.map((s) => s.value)).toEqual([2])
})
```
+When the test cares about what the user actually sees rendered, reach for `tooltip.element.textContent`.
+
### Click a data point
-Use `clickAtIndex` to fire a click on a specific column and assert that the chart's `onPointClick` callback received the expected `PointClickData` (`seriesIndex`, `dataIndex`, `series`, `value`, `label`, `crossSeriesData`). `clickAtIndex` resolves after the click handler runs.
+Use `chart.clickAtIndex` to fire a click on a specific column and assert that the chart's `onPointClick` callback received the expected `PointClickData` (`seriesIndex`, `dataIndex`, `series`, `value`, `label`, `crossSeriesData`). It resolves after the click handler runs.
```tsx
it('invokes onPointClick with the clicked column', async () => {
@@ -144,7 +129,7 @@ it('invokes onPointClick with the clicked column', async () => {
<LineChart series={SERIES} labels={LABELS} theme={THEME} onPointClick={onPointClick} />
)
- await clickAtIndex(chart.element, 1, LABELS.length)
+ await chart.clickAtIndex(1)
expect(onPointClick).toHaveBeenCalledWith(expect.objectContaining({ dataIndex: 1, label: 'Tue', value: 2 }))
})
```
@@ -180,7 +165,7 @@ it('reports render errors through onError', () => {
<LineChart series={SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} onError={onError} />
)
- hoverAtIndex(chart.element, 1, LABELS.length)
+ chart.hoverAtIndex(1)
expect(onError).toHaveBeenCalled()
})
```
diff --git a/frontend/src/lib/hog-charts/testing/accessor.ts b/frontend/src/lib/hog-charts/testing/accessor.ts
index 8940a2d73b88..046d4c7069d5 100644
--- a/frontend/src/lib/hog-charts/testing/accessor.ts
+++ b/frontend/src/lib/hog-charts/testing/accessor.ts
@@ -6,12 +6,15 @@
// contract — renaming them breaks consumers' tests. Keep in sync with the
// overlay components that emit them.
+import { fireEvent } from '@testing-library/react'
+
import type { TooltipContext } from '../core/types'
-import { waitForHogChartTooltip } from './tooltip'
+import { dimensions } from './jsdom'
+import { type HogChartTooltip, waitForHogChartTooltip } from './tooltip'
-/** Tooltip handle returned by `chart.waitForTooltip()` — every field of the structured
- * `TooltipContext` plus the rendered portal element, so tests can assert on either. */
-export type TooltipSnapshot<Meta = unknown> = TooltipContext<Meta> & { element: HTMLElement }
+/** Handle returned by `chart.waitForTooltip()` — every field of the structured `TooltipContext`,
+ * plus the rendered portal `element` and an `isPinned` snapshot. */
+export type TooltipSnapshot<Meta = unknown> = TooltipContext<Meta> & HogChartTooltip
interface ReferenceLineSummary {
label: string | null
@@ -56,12 +59,28 @@ export interface HogChart<Meta = unknown> {
anomalyPoints(): AnomalyPointSummary[]
/** Annotation badges currently rendered. */
annotationBadges(): HTMLElement[]
- /** Wait for the tooltip to mount, then return a snapshot of both the structured
- * `TooltipContext` the chart computed and the rendered portal element. Only available
- * when the chart was rendered via `renderHogChart`; throws otherwise. */
+ /** Fire a `mouseMove` over the data point at `index`. Only available when the chart was
+ * rendered via `renderHogChart` (it reads label count from `ui.props.labels`); the
+ * module-level `hoverAtIndex(wrapper, index, totalLabels)` is the explicit alternative. */
+ hoverAtIndex(index: number): void
+ /** 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>
+ /** 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
+ * chart was rendered via `renderHogChart`; throws otherwise. */
waitForTooltip(timeout?: number): Promise<TooltipSnapshot<Meta>>
}
+export interface GetHogChartOptions<Meta = unknown> {
+ /** Returns the most recent `TooltipContext` the chart computed (set up by `renderHogChart`'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
+}
+
const SERIES_COUNT_RE = /Chart with (\d+) data series/i
function findCanvas(scope: HTMLElement): HTMLCanvasElement | null {
@@ -100,9 +119,17 @@ function readReferenceLine(el: HTMLElement): ReferenceLineSummary {
return { color, orientation, position, label }
}
+function clientForIndex(totalLabels: number, index: number): { clientX: number; clientY: number } {
+ const step = dimensions.plotWidth / Math.max(1, totalLabels - 1)
+ return {
+ clientX: dimensions.plotLeft + step * index,
+ clientY: dimensions.plotTop + dimensions.plotHeight / 2,
+ }
+}
+
export function getHogChart<Meta = unknown>(
scope: HTMLElement = document.body,
- getLastTooltipContext: () => TooltipContext<Meta> | null = () => null
+ options: GetHogChartOptions<Meta> = {}
): HogChart<Meta> {
const canvas = findCanvas(scope)
if (!canvas) {
@@ -119,6 +146,8 @@ export function getHogChart<Meta = unknown>(
const match = SERIES_COUNT_RE.exec(ariaLabel)
const seriesCount = match ? Number(match[1]) : 0
+ const { getLastTooltipContext, totalLabels } = options
+
return {
element: wrapper,
seriesCount,
@@ -152,15 +181,35 @@ export function getHogChart<Meta = unknown>(
color: el.style.backgroundColor,
})),
annotationBadges: () => Array.from(wrapper.querySelectorAll<HTMLElement>('.AnnotationsBadge')),
+ hoverAtIndex(index: number): void {
+ if (totalLabels === undefined) {
+ throw new Error('chart.hoverAtIndex requires renderHogChart (which captures labels.length)')
+ }
+ fireEvent.mouseMove(wrapper, clientForIndex(totalLabels, index))
+ },
+ async clickAtIndex(index: number): Promise<void> {
+ if (totalLabels === undefined) {
+ throw new Error('chart.clickAtIndex requires renderHogChart (which captures labels.length)')
+ }
+ fireEvent.mouseMove(wrapper, clientForIndex(totalLabels, index))
+ // Wait for the hover state to flush — the click handler reads live tooltipCtx
+ // synchronously to choose between pinning and onPointClick.
+ await waitForHogChartTooltip()
+ fireEvent.click(wrapper)
+ },
async waitForTooltip(timeout?: number): Promise<TooltipSnapshot<Meta>> {
const element = await waitForHogChartTooltip(timeout)
- const ctx = getLastTooltipContext()
+ const ctx = getLastTooltipContext?.() ?? null
if (!ctx) {
throw new Error(
- 'TooltipContext not captured. Render the chart via `renderHogChart` to enable tooltip context capture.'
+ 'TooltipContext not captured. Render via renderHogChart to enable tooltip context capture.'
)
}
- return { ...ctx, element }
+ return {
+ ...ctx,
+ element,
+ isPinned: element.classList.contains('hog-charts-tooltip--pinned'),
+ }
},
}
}
diff --git a/frontend/src/lib/hog-charts/testing/index.ts b/frontend/src/lib/hog-charts/testing/index.ts
index 7019947b3c67..3f893cce015b 100644
--- a/frontend/src/lib/hog-charts/testing/index.ts
+++ b/frontend/src/lib/hog-charts/testing/index.ts
@@ -1,7 +1,7 @@
-export { dimensions, makeSeries, mockRect, setupJsdom, setupSyncRaf } from './jsdom'
+export { dimensions, ensureJsdom, makeSeries, mockRect, setupJsdom, setupSyncRaf } from './jsdom'
export { clickAtIndex, hoverAtIndex } from './interactions'
export { getHogChart } from './accessor'
-export type { HogChart, TooltipSnapshot } from './accessor'
+export type { GetHogChartOptions, HogChart, TooltipSnapshot } from './accessor'
export { renderHogChart } from './render'
export { makeOverlayContext, renderOverlayInChart } from './overlay'
export type { OverlayContextOverrides } from './overlay'
diff --git a/frontend/src/lib/hog-charts/testing/jsdom.ts b/frontend/src/lib/hog-charts/testing/jsdom.ts
index 0c6dae8b448b..2316012538d1 100644
--- a/frontend/src/lib/hog-charts/testing/jsdom.ts
+++ b/frontend/src/lib/hog-charts/testing/jsdom.ts
@@ -55,3 +55,19 @@ export function setupSyncRaf(): () => void {
global.requestAnimationFrame = original
}
}
+
+let jsdomReady = false
+
+/** Idempotent sibling of {@link setupJsdom} + {@link setupSyncRaf}. Called automatically by
+ * `renderHogChart` so simple tests don't need a beforeEach for the mocks; they're installed
+ * once for the test run and never torn down (cheap, and `getBoundingClientRect` stubbing is
+ * harmless to leave on for non-chart code in the same file). Tests that want fine-grained
+ * teardown can use the explicit `setupJsdom()` / `setupSyncRaf()` pair instead. */
+export function ensureJsdom(): void {
+ if (jsdomReady) {
+ return
+ }
+ jsdomReady = true
+ setupJsdom()
+ setupSyncRaf()
+}
diff --git a/frontend/src/lib/hog-charts/testing/render.ts b/frontend/src/lib/hog-charts/testing/render.ts
index 0f9813c66a13..30eee680edae 100644
--- a/frontend/src/lib/hog-charts/testing/render.ts
+++ b/frontend/src/lib/hog-charts/testing/render.ts
@@ -1,20 +1,30 @@
-import { render, type RenderResult } from '@testing-library/react'
+import { cleanup, render, type RenderResult } from '@testing-library/react'
import React, { type ReactElement, type ReactNode } from 'react'
import type { TooltipContext } from '../core/types'
import { DefaultTooltip } from '../overlays/DefaultTooltip'
import { getHogChart, type HogChart } from './accessor'
+import { ensureJsdom } from './jsdom'
+import { HOG_CHARTS_TOOLTIP_SELECTOR } from './tooltip'
-/** Render a hog-charts component and return Testing Library's `RenderResult`
- * with a `chart` accessor attached. Throws if the rendered component doesn't
- * emit a hog-charts canvas — use plain `render` for non-chart components.
+/** Render a hog-charts component and return Testing Library's `RenderResult` with a `chart`
+ * accessor attached. Throws if the rendered tree doesn't contain a hog-charts canvas.
*
- * The `tooltip` render prop is intercepted so `chart.waitForTooltip()` can
- * return the structured `TooltipContext` the chart computed; any user-supplied
- * tooltip prop is still invoked for its rendered DOM. */
+ * 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 renderHogChart<Meta = unknown>(ui: ReactElement): RenderResult & { chart: HogChart<Meta> } {
+ ensureJsdom()
+ cleanup()
+ document.querySelectorAll(HOG_CHARTS_TOOLTIP_SELECTOR).forEach((el) => el.remove())
+
+ // Intercept the (optional) `tooltip` render prop so `chart.waitForTooltip()` can return
+ // the structured `TooltipContext` the chart computed. When the consumer passes a tooltip
+ // we still call it for the rendered DOM; otherwise we fall through to DefaultTooltip,
+ // matching the chart's natural default.
let lastTooltipContext: TooltipContext<Meta> | null = null
- const userTooltip = (ui.props as { tooltip?: (ctx: TooltipContext<Meta>) => ReactNode }).tooltip
+ const props = ui.props as { tooltip?: (ctx: TooltipContext<Meta>) => ReactNode; labels?: string[] }
+ const userTooltip = props.tooltip
const captureTooltip = (ctx: TooltipContext<Meta>): ReactNode => {
lastTooltipContext = ctx
return userTooltip ? userTooltip(ctx) : DefaultTooltip(ctx as TooltipContext)
@@ -23,6 +33,9 @@ export function renderHogChart<Meta = unknown>(ui: ReactElement): RenderResult &
const result = render(wrapped)
return {
...result,
- chart: getHogChart<Meta>(result.container, () => lastTooltipContext),
+ chart: getHogChart<Meta>(result.container, {
+ getLastTooltipContext: () => lastTooltipContext,
+ totalLabels: props.labels?.length,
+ }),
}
}