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(hog-charts): expand LineChart coverage; add overlay test helpers (#57539)

Sam Pennington4c2598ee494d
diff --git a/frontend/src/lib/hog-charts/charts/LineChart.test.tsx b/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
index c2d180a85c8a..8037fe717bdb 100644
--- a/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
@@ -1,7 +1,16 @@
-import { cleanup, render } from '@testing-library/react'
+import { cleanup } from '@testing-library/react'
-import type { ChartTheme, Series } from '../core/types'
-import { renderHogChart, setupJsdom, setupSyncRaf } from '../testing'
+import type { ChartTheme, Series, TooltipContext } from '../core/types'
+import { ReferenceLine } from '../overlays/ReferenceLine'
+import {
+ clickAtIndex,
+ getHogChartTooltip,
+ hoverAtIndex,
+ renderHogChart,
+ setupJsdom,
+ setupSyncRaf,
+ waitForHogChartTooltip,
+} from '../testing'
import { LineChart } from './LineChart'
const THEME: ChartTheme = {
@@ -58,10 +67,10 @@ describe('LineChart', () => {
})
it('forwards `dataAttr` to the chart wrapper for product-test selection', () => {
- const { container } = render(
+ const { chart } = renderHogChart(
<LineChart series={SERIES} labels={LABELS} theme={THEME} dataAttr="line-chart-instance" />
)
- expect(container.querySelector('[data-attr="line-chart-instance"]')).not.toBeNull()
+ expect(chart.element.getAttribute('data-attr')).toBe('line-chart-instance')
})
it('applies a default percent formatter when consumer omits one in percent stack mode', () => {
@@ -87,7 +96,159 @@ describe('LineChart', () => {
it('tolerates NaN data values without throwing', () => {
const broken: Series[] = [{ key: 'a', label: 'A', data: [Number.NaN, Number.NaN, Number.NaN] }]
- const { container } = render(<LineChart series={broken} labels={LABELS} theme={THEME} />)
- expect(container.querySelector('canvas')).not.toBeNull()
+ const { chart } = renderHogChart(<LineChart series={broken} labels={LABELS} theme={THEME} />)
+ expect(chart.seriesCount).toBe(1)
+ })
+
+ describe('axis configuration', () => {
+ it.each([
+ ['hideXAxis', { hideXAxis: true }, 'xTicks'],
+ ['hideYAxis', { hideYAxis: true }, 'yTicks'],
+ ] as const)('hides ticks when %s is true', (_, config, accessor) => {
+ const { chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME} config={config} />
+ )
+ expect(chart[accessor]()).toHaveLength(0)
+ })
+
+ it('applies xTickFormatter to x-axis ticks', () => {
+ const { chart } = renderHogChart(
+ <LineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ xTickFormatter: (_l, i) => `tick-${i}` }}
+ />
+ )
+ expect(chart.xTicks()).toEqual(['tick-0', 'tick-1', 'tick-2'])
+ })
+
+ it('renders a right axis when a series sets yAxisId: right', () => {
+ const series: Series[] = [
+ { key: 'a', label: 'A', data: [10, 20, 30] },
+ { key: 'b', label: 'B', data: [1000, 2000, 3000], yAxisId: 'right' },
+ ]
+ const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
+ expect(chart.hasRightAxis).toBe(true)
+ expect(chart.yRightTicks().length).toBeGreaterThan(0)
+ })
+
+ it('renders without crashing in yScaleType log with positive data', () => {
+ const series: Series[] = [{ key: 'a', label: 'A', data: [1, 10, 100] }]
+ const { chart } = renderHogChart(
+ <LineChart series={series} labels={LABELS} theme={THEME} config={{ yScaleType: 'log' }} />
+ )
+ const ticks = chart.yTicks()
+ expect(ticks.length).toBeGreaterThan(0)
+ for (const t of ticks) {
+ expect(Number.isFinite(parseFloat(t.replace(/[^0-9.\-eE]/g, '')))).toBe(true)
+ }
+ })
+ })
+
+ 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)
+ const tooltip = await waitForHogChartTooltip()
+ expect(tooltip.textContent).toContain('Tue')
+ })
+
+ it('invokes onPointClick with the clicked column', async () => {
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME} onPointClick={onPointClick} />
+ )
+ await clickAtIndex(chart.element, 1, LABELS.length)
+ expect(onPointClick).toHaveBeenCalledWith(
+ expect.objectContaining({ dataIndex: 1, label: 'Tue', value: 20 })
+ )
+ })
+
+ it('passes hovered seriesData to a custom tooltip render prop', async () => {
+ const tooltip = (ctx: TooltipContext): React.ReactNode => (
+ <div data-attr="custom-tooltip">{ctx.seriesData.length}</div>
+ )
+ const { chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} />
+ )
+ hoverAtIndex(chart.element, 1, LABELS.length)
+ const node = await waitForHogChartTooltip()
+ expect(node.querySelector('[data-attr="custom-tooltip"]')?.textContent).toBe(String(SERIES.length))
+ })
+
+ it('pins the tooltip on click when tooltip.pinnable is true', async () => {
+ const { chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ tooltip: { pinnable: true } }} />
+ )
+ hoverAtIndex(chart.element, 1, LABELS.length)
+ await waitForHogChartTooltip()
+ await clickAtIndex(chart.element, 1, LABELS.length)
+ expect(getHogChartTooltip()?.classList.contains('hog-charts-tooltip--pinned')).toBe(true)
+ })
+
+ it('does not crash on hover for visibility.fromStack series', async () => {
+ const series: Series[] = [
+ { key: 'a', label: 'A', data: [10, 20, 30] },
+ { key: 'b', label: 'B', data: [5, 15, 25], visibility: { fromStack: true } },
+ ]
+ const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
+ hoverAtIndex(chart.element, 1, LABELS.length)
+ const tooltip = await waitForHogChartTooltip()
+ expect(tooltip.textContent).toContain('Tue')
+ })
+
+ it('omits a series from tooltip when visibility.fromTooltip is true', async () => {
+ const series: Series[] = [
+ { key: 'a', label: 'A', data: [10, 20, 30] },
+ { key: 'b', label: 'B', data: [5, 15, 25], visibility: { fromTooltip: true } },
+ ]
+ const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)
+ hoverAtIndex(chart.element, 1, LABELS.length)
+ const tooltip = await waitForHogChartTooltip()
+ expect(tooltip.textContent).toContain('A')
+ expect(tooltip.textContent).not.toContain('B')
+ })
+ })
+
+ describe('children & error boundary', () => {
+ it('renders custom overlay children', () => {
+ const { chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME}>
+ <div data-attr="custom-child" />
+ </LineChart>
+ )
+ expect(chart.element.querySelector('[data-attr="custom-child"]')).not.toBeNull()
+ })
+
+ it('renders a ReferenceLine child via the accessor', () => {
+ const { chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME}>
+ <ReferenceLine value={15} label="Target" />
+ </LineChart>
+ )
+ const lines = chart.referenceLines()
+ expect(lines).toHaveLength(1)
+ expect(lines[0].label).toBe('Target')
+ expect(lines[0].orientation).toBe('horizontal')
+ })
+
+ it('reports render errors through onError', () => {
+ const onError = jest.fn()
+ const tooltip = (): React.ReactNode => {
+ throw new Error('boom')
+ }
+ // ChartErrorBoundary surfaces the error to onError; React still logs it.
+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
+ try {
+ const { chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} onError={onError} />
+ )
+ hoverAtIndex(chart.element, 1, LABELS.length)
+ expect(onError).toHaveBeenCalled()
+ } finally {
+ consoleErrorSpy.mockRestore()
+ }
+ })
})
})
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
index 936bcd64b3e8..4894dd536089 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -225,7 +225,7 @@ describe('TimeSeriesLineChart', () => {
['omitted', undefined],
['empty', [] as AnomalyMarker[]],
])('does not render anomaly points when anomalies is %s', (_, anomalies) => {
- const { container } = renderHogChart(
+ const { chart } = renderHogChart(
<TimeSeriesLineChart
series={SERIES}
labels={LABELS}
@@ -233,7 +233,7 @@ describe('TimeSeriesLineChart', () => {
config={anomalies === undefined ? undefined : { anomalies }}
/>
)
- expect(container.querySelectorAll('[data-attr="hog-chart-anomaly-point"]')).toHaveLength(0)
+ expect(chart.anomalyPoints()).toHaveLength(0)
})
it('renders one anomaly point per marker', () => {
@@ -241,13 +241,13 @@ describe('TimeSeriesLineChart', () => {
{ dataIndex: 1, value: 2, color: '#f00', yAxisId: 'left' },
{ dataIndex: 2, value: 3, color: '#0f0', yAxisId: 'left' },
]
- const { container } = renderHogChart(
+ const { chart } = renderHogChart(
<TimeSeriesLineChart series={SERIES} labels={LABELS} theme={THEME} config={{ anomalies: markers }} />
)
- const dots = container.querySelectorAll<HTMLElement>('[data-attr="hog-chart-anomaly-point"]')
- expect(dots).toHaveLength(2)
- expect(dots[0].style.backgroundColor).toBe('rgb(255, 0, 0)')
- expect(dots[1].style.backgroundColor).toBe('rgb(0, 255, 0)')
+ const points = chart.anomalyPoints()
+ expect(points).toHaveLength(2)
+ expect(points[0].color).toBe('rgb(255, 0, 0)')
+ expect(points[1].color).toBe('rgb(0, 255, 0)')
})
})
diff --git a/frontend/src/lib/hog-charts/overlays/ReferenceLine.test.tsx b/frontend/src/lib/hog-charts/overlays/ReferenceLine.test.tsx
index b755a56ecc47..cf50f58c0d82 100644
--- a/frontend/src/lib/hog-charts/overlays/ReferenceLine.test.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ReferenceLine.test.tsx
@@ -1,9 +1,8 @@
-import { cleanup, render } from '@testing-library/react'
+import { cleanup, type RenderResult } from '@testing-library/react'
import React from 'react'
-import type { BaseChartContext, ChartLayoutContextValue } from '../core/chart-context'
-import { ChartHoverContext, ChartLayoutContext } from '../core/chart-context'
-import type { ChartTheme } from '../core/types'
+import type { BaseChartContext } from '../core/chart-context'
+import { makeOverlayContext, renderOverlayInChart } from '../testing'
import { ReferenceLine, ReferenceLines } from './ReferenceLine'
const DIMENSIONS = {
@@ -15,39 +14,23 @@ const DIMENSIONS = {
plotHeight: 352,
}
-const THEME: ChartTheme = { colors: ['#000'], backgroundColor: '#ffffff' }
-
// Simple linear y-scale: 0 -> plotBottom (368), 100 -> plotTop (16)
const yScale = (v: number): number => 368 - (v / 100) * 352
-const CONTEXT: BaseChartContext = {
- dimensions: DIMENSIONS,
- labels: ['Mon', 'Tue', 'Wed'],
- series: [],
- scales: {
+const CONTEXT: BaseChartContext = makeOverlayContext(
+ {
x: (label: string) => (({ Mon: 100, Tue: 400, Wed: 700 }) as Record<string, number | undefined>)[label],
y: yScale,
yTicks: () => [0, 50, 100],
},
- theme: THEME,
- resolveValue: (s, i) => s.data[i] ?? 0,
- canvasBounds: () => null,
- axisOrientation: 'vertical',
- isPercent: false,
- hoverIndex: -1,
-}
-
-function toLayout(ctx: BaseChartContext): ChartLayoutContextValue {
- const { hoverIndex: _hoverIndex, ...layout } = ctx
- return layout
-}
-
-function renderInChart(node: React.ReactNode, ctx: BaseChartContext = CONTEXT): ReturnType<typeof render> {
- return render(
- <ChartLayoutContext.Provider value={toLayout(ctx)}>
- <ChartHoverContext.Provider value={{ hoverIndex: ctx.hoverIndex }}>{node}</ChartHoverContext.Provider>
- </ChartLayoutContext.Provider>
- )
+ {
+ dimensions: DIMENSIONS,
+ labels: ['Mon', 'Tue', 'Wed'],
+ }
+)
+
+function renderInChart(node: React.ReactNode, ctx: BaseChartContext = CONTEXT): RenderResult {
+ return renderOverlayInChart(node, ctx)
}
function lineDiv(container: HTMLElement, side: 'top' | 'left'): HTMLDivElement | null {
diff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
index d35973d71102..975931b93e3a 100644
--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
@@ -1,9 +1,9 @@
-import { cleanup, render } from '@testing-library/react'
+import { cleanup, type RenderResult } from '@testing-library/react'
import React from 'react'
-import type { BaseChartContext, ChartLayoutContextValue } from '../core/chart-context'
-import { ChartHoverContext, ChartLayoutContext } from '../core/chart-context'
-import type { ChartTheme, ResolvedSeries, ResolveValueFn } from '../core/types'
+import type { BaseChartContext } from '../core/chart-context'
+import type { ChartScales, ChartTheme, ResolvedSeries, ResolveValueFn } from '../core/types'
+import { makeOverlayContext, type OverlayContextOverrides, renderOverlayInChart } from '../testing'
import { ValueLabels } from './ValueLabels'
const DIMENSIONS = {
@@ -22,40 +22,21 @@ const xScale = (label: string): number | undefined => X_POSITIONS[label]
// Left axis: 0 -> 368, 100 -> 16
const yScale = (v: number): number => 368 - (v / 100) * 352
-const DEFAULT_THEME: ChartTheme = { colors: ['#000'], backgroundColor: '#ffffff' }
-const DEFAULT_RESOLVE: ResolveValueFn = (s, i) => s.data[i] ?? 0
-
-function makeContext(series: ResolvedSeries[], overrides: Partial<BaseChartContext> = {}): BaseChartContext {
- return {
+function makeContext(
+ series: ResolvedSeries[],
+ overrides: OverlayContextOverrides & { scales?: ChartScales } = {}
+): BaseChartContext {
+ const { scales, ...rest } = overrides
+ return makeOverlayContext(scales ?? { x: xScale, y: yScale, yTicks: () => [0, 50, 100] }, {
dimensions: DIMENSIONS,
labels: LABELS,
series,
- scales: {
- x: xScale,
- y: yScale,
- yTicks: () => [0, 50, 100],
- },
- theme: DEFAULT_THEME,
- resolveValue: DEFAULT_RESOLVE,
- canvasBounds: () => null,
- axisOrientation: 'vertical',
- isPercent: false,
- hoverIndex: -1,
- ...overrides,
- }
-}
-
-function toLayout(ctx: BaseChartContext): ChartLayoutContextValue {
- const { hoverIndex: _hoverIndex, ...layout } = ctx
- return layout
+ ...rest,
+ })
}
-function renderInChart(context: BaseChartContext, node: React.ReactNode): ReturnType<typeof render> {
- return render(
- <ChartLayoutContext.Provider value={toLayout(context)}>
- <ChartHoverContext.Provider value={{ hoverIndex: context.hoverIndex }}>{node}</ChartHoverContext.Provider>
- </ChartLayoutContext.Provider>
- )
+function renderInChart(context: BaseChartContext, node: React.ReactNode): RenderResult {
+ return renderOverlayInChart(node, context)
}
function labelDivs(container: HTMLElement): HTMLDivElement[] {
diff --git a/frontend/src/lib/hog-charts/testing/accessor.ts b/frontend/src/lib/hog-charts/testing/accessor.ts
index 0fc2d26adf49..82ed1e768076 100644
--- a/frontend/src/lib/hog-charts/testing/accessor.ts
+++ b/frontend/src/lib/hog-charts/testing/accessor.ts
@@ -22,6 +22,12 @@ interface ValueLabelSummary {
color: string
}
+interface AnomalyPointSummary {
+ element: HTMLElement
+ /** Inline style backgroundColor (matches the marker's series color). */
+ color: string
+}
+
export interface HogChart {
/** The wrapper div of this chart. */
element: HTMLElement
@@ -39,6 +45,8 @@ export interface HogChart {
referenceLines(): ReferenceLineSummary[]
/** All value-label overlays currently rendered for this chart. */
valueLabels(): ValueLabelSummary[]
+ /** All anomaly point markers currently rendered (TimeSeriesLineChart only). */
+ anomalyPoints(): AnomalyPointSummary[]
/** Annotation badges currently rendered. */
annotationBadges(): HTMLElement[]
}
@@ -124,6 +132,11 @@ export function getHogChart(scope: HTMLElement = document.body): HogChart {
text: el.textContent ?? '',
color: el.style.backgroundColor,
})),
+ anomalyPoints: () =>
+ Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-anomaly-point"]')).map((el) => ({
+ element: el,
+ color: el.style.backgroundColor,
+ })),
annotationBadges: () => Array.from(wrapper.querySelectorAll<HTMLElement>('.AnnotationsBadge')),
}
}
diff --git a/frontend/src/lib/hog-charts/testing/index.ts b/frontend/src/lib/hog-charts/testing/index.ts
index 22c27db9cc0c..7a2682067a0d 100644
--- a/frontend/src/lib/hog-charts/testing/index.ts
+++ b/frontend/src/lib/hog-charts/testing/index.ts
@@ -3,6 +3,8 @@ export { clickAtIndex, hoverAtIndex } from './interactions'
export { getHogChart } from './accessor'
export type { HogChart } from './accessor'
export { renderHogChart } from './render'
+export { makeOverlayContext, renderOverlayInChart } from './overlay'
+export type { OverlayContextOverrides } from './overlay'
export {
createHogChartTooltip,
getHogChartTooltip,
diff --git a/frontend/src/lib/hog-charts/testing/overlay.tsx b/frontend/src/lib/hog-charts/testing/overlay.tsx
new file mode 100644
index 000000000000..26a72e58b67b
--- /dev/null
+++ b/frontend/src/lib/hog-charts/testing/overlay.tsx
@@ -0,0 +1,52 @@
+import { render, type RenderResult } from '@testing-library/react'
+import type { ReactNode } from 'react'
+
+import { ChartHoverContext, ChartLayoutContext } from '../core/chart-context'
+import type { BaseChartContext, ChartLayoutContextValue } from '../core/chart-context'
+import type { ChartScales, ChartTheme, ResolvedSeries, ResolveValueFn } from '../core/types'
+import { dimensions as DEFAULT_DIMENSIONS } from './jsdom'
+
+const DEFAULT_THEME: ChartTheme = { colors: ['#000'], backgroundColor: '#ffffff' }
+const DEFAULT_RESOLVE: ResolveValueFn = (s, i) => s.data[i] ?? 0
+
+export interface OverlayContextOverrides {
+ dimensions?: BaseChartContext['dimensions']
+ labels?: string[]
+ series?: ResolvedSeries[]
+ theme?: ChartTheme
+ resolveValue?: ResolveValueFn
+ canvasBounds?: () => DOMRect | null
+ axisOrientation?: 'vertical' | 'horizontal'
+ isPercent?: boolean
+ hoverIndex?: number
+}
+
+/** Build a fully-populated overlay context with sensible defaults. Required:
+ * `scales` (the overlay-under-test almost always needs control over these). */
+export function makeOverlayContext(scales: ChartScales, overrides: OverlayContextOverrides = {}): BaseChartContext {
+ return {
+ dimensions: overrides.dimensions ?? DEFAULT_DIMENSIONS,
+ labels: overrides.labels ?? [],
+ series: overrides.series ?? [],
+ scales,
+ theme: overrides.theme ?? DEFAULT_THEME,
+ resolveValue: overrides.resolveValue ?? DEFAULT_RESOLVE,
+ canvasBounds: overrides.canvasBounds ?? (() => null),
+ axisOrientation: overrides.axisOrientation ?? 'vertical',
+ isPercent: overrides.isPercent ?? false,
+ hoverIndex: overrides.hoverIndex ?? -1,
+ }
+}
+
+/** Render an overlay component with explicit chart context — used to test overlays
+ * in isolation without booting a real chart. Pass hand-rolled scales so you can
+ * assert exact pixel positions without depending on d3's tick algorithm. */
+export function renderOverlayInChart(node: ReactNode, ctx: BaseChartContext): RenderResult {
+ const { hoverIndex, ...layout } = ctx
+ const layoutValue: ChartLayoutContextValue = layout
+ return render(
+ <ChartLayoutContext.Provider value={layoutValue}>
+ <ChartHoverContext.Provider value={{ hoverIndex }}>{node}</ChartHoverContext.Provider>
+ </ChartLayoutContext.Provider>
+ )
+}