: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(insights): add SQL chart test harness + bar coverage (#65002)
Sam Pennington141129b8b9e7
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsxnew file mode 100644index 000000000000..ce2721eafefb--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx@@ -0,0 +1,164 @@+import '@testing-library/jest-dom'++import { cleanup, configure, fireEvent, screen, waitFor } from '@testing-library/react'++import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { ChartSettings } from '~/queries/schema/schema-general'+import {+ type DataVizFixture,+ buildDataVisualizationQuery,+ getHogChart,+ HOVER,+ MONTHS,+ renderDataVisualization,+ sqlChart,+} from '~/test/insight-testing'+import { ChartDisplayType } from '~/types'++// Neither timeout is set globally (jest.setup leaves asyncUtilTimeout at 1s, jest.config has no+// testTimeout → 5s): this heavy ~7-logic mount needs findByRole headroom beyond 1s on CI, and+// sqlChart.hoverTooltip's internal waits (findByRole + tooltip poll) can sum past the 5s default.+configure({ asyncUtilTimeout: 5000 })+jest.setTimeout(15000)++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++function barFixture(columns: { name: string; valueAt: (i: number) => unknown }[]): DataVizFixture {+ return {+ columns: ['month', ...columns.map((c) => c.name)],+ types: [['month', 'Date'], ...columns.map((c): [string, string] => [c.name, 'UInt64'])],+ results: MONTHS.map((m, i) => [m, ...columns.map((c) => c.valueAt(i))]),+ }+}++const twoSeries = (): DataVizFixture =>+ barFixture([+ { name: 'a', valueAt: (i) => (i + 1) * 100 },+ { name: 'b', valueAt: (i) => (i + 1) * 10 },+ ])++const renderBar = (+ display: ChartDisplayType,+ chartSettings: ChartSettings,+ fixture: DataVizFixture+): ReturnType<typeof renderDataVisualization> =>+ renderDataVisualization({+ query: buildDataVisualizationQuery({+ display,+ chartSettings: { xAxis: { column: 'month' }, ...chartSettings },+ }),+ response: fixture,+ })++describe('SqlBarGraph', () => {+ describe('bar layouts', () => {+ it.each([+ { name: 'grouped', display: ChartDisplayType.ActionsBar, extra: {} },+ { name: 'stacked', display: ChartDisplayType.ActionsStackedBar, extra: {} },+ {+ name: 'percent (100% stacked)',+ display: ChartDisplayType.ActionsStackedBar,+ extra: { stackBars100: true },+ },+ ])('renders both series in the $name layout', async ({ display, extra }) => {+ renderBar(display, { yAxis: [{ column: 'a' }, { column: 'b' }], ...extra }, twoSeries())++ await screen.findByRole('img', { name: /chart with 2 data series/i })+ await waitFor(() => expect(getHogChart().yTicks().length).toBeGreaterThan(0))+ })++ it('renders percentage y-axis ticks for the 100%-stacked layout', async () => {+ renderBar(+ ChartDisplayType.ActionsStackedBar,+ { yAxis: [{ column: 'a' }, { column: 'b' }], stackBars100: true },+ twoSeries()+ )++ await screen.findByRole('img', { name: /chart with 2 data series/i })+ await waitFor(() => expect(getHogChart().yTicks().length).toBeGreaterThan(0))+ for (const tick of getHogChart().yTicks()) {+ expect(tick).toMatch(/%$/)+ }+ })+ })++ describe('tooltip', () => {+ // Grouped/stacked bars split the band, so a band-center hover only deterministically lands on+ // a single bar — assert tooltip content with one series, layout/legend with two.+ it('shows the value, swatch, and x-label for a single series', async () => {+ renderBar(+ ChartDisplayType.ActionsBar,+ { yAxis: [{ column: 'a' }] },+ barFixture([{ name: 'a', valueAt: (i) => (i + 1) * 1000 }])+ )++ await screen.findByRole('img', { name: /chart with/i })+ const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)++ expect(tooltip.value('a')).toBe('3,000')+ expect(tooltip.label()).toBe('2025-12-01')+ expect(tooltip.swatchColors()).toHaveLength(1)+ })+ })++ describe('legend', () => {+ const getLegend = (container: HTMLElement): HTMLElement =>+ container.querySelector<HTMLElement>('[data-attr="hog-chart-timeseries-bar-legend"]')!++ it('renders an in-chart legend listing every series when showLegend is set', async () => {+ const { container } = renderBar(+ ChartDisplayType.ActionsStackedBar,+ { yAxis: [{ column: 'a' }, { column: 'b' }], showLegend: true },+ twoSeries()+ )++ await screen.findByRole('img', { name: /chart with 2 data series/i })+ const labels = [...getLegend(container).querySelectorAll('button')].map((b) => b.textContent)+ expect(labels).toEqual(['a', 'b'])+ })++ it('hides a series when its legend item is toggled off', async () => {+ const { container } = renderBar(+ ChartDisplayType.ActionsStackedBar,+ { yAxis: [{ column: 'a' }, { column: 'b' }], showLegend: true },+ twoSeries()+ )++ await screen.findByRole('img', { name: /chart with 2 data series/i })+ const bButton = [...getLegend(container).querySelectorAll('button')].find((b) =>+ b.textContent?.includes('b')+ )!+ fireEvent.click(bButton)++ await waitFor(() => expect(getHogChart().seriesCount).toBe(1))+ })+ })++ describe('goal lines', () => {+ it('renders a goal line as a horizontal reference line', async () => {+ renderBar(+ ChartDisplayType.ActionsBar,+ { yAxis: [{ column: 'a' }], goalLines: [{ label: 'Target', value: 250, displayIfCrossed: true }] },+ barFixture([{ name: 'a', valueAt: (i) => (i + 1) * 100 }])+ )++ await screen.findByRole('img', { name: /chart with/i })+ const lines = getHogChart().referenceLines()+ expect(lines.map((l) => l.label)).toEqual(['Target'])+ expect(lines[0].orientation).toBe('horizontal')+ })+ })+})diff --git a/frontend/src/test/insight-testing/index.ts b/frontend/src/test/insight-testing/index.tsindex 2e04a48718ce..09d62c2f3e55 100644--- a/frontend/src/test/insight-testing/index.ts+++ b/frontend/src/test/insight-testing/index.ts@@ -13,6 +13,8 @@ export {renderWithInsights,} from './render-insight'export type { InsightQuery, RenderInsightProps, RenderWithInsightsProps } from './render-insight'+export { buildDataVisualizationQuery, HOVER, MONTHS, renderDataVisualization } from './render-data-visualization'+export type { DataVizFixture } from './render-data-visualization'export {breakdown,chart,@@ -23,6 +25,7 @@ export {legend,searchAndSelect,series,+ sqlChart,} from './interactions'export { personsModal } from './elements'export { buildActorsResponse, setupInsightMocks } from './mocks'diff --git a/frontend/src/test/insight-testing/interactions.ts b/frontend/src/test/insight-testing/interactions.tsindex d8d72e448b69..f76b107d1ae7 100644--- a/frontend/src/test/insight-testing/interactions.ts+++ b/frontend/src/test/insight-testing/interactions.ts@@ -3,6 +3,8 @@ import userEvent from '@testing-library/user-event'import {clickAtIndex,+ createDefaultTooltipAccessor,+ type DefaultTooltipAccessor,getHogChartTooltip,hoverUntilTooltip,waitForHogChartTooltip,@@ -167,3 +169,15 @@ export const chart = {fireEvent.click(clickable)},}++/** 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. */+export const sqlChart = {+ async hoverTooltip(index: number, totalLabels: number): Promise<DefaultTooltipAccessor> {+ const canvas = await screen.findByRole('img', { name: /chart with/i }, { timeout: DEBOUNCE_TIMEOUT })+ const wrapper = canvas.parentElement!+ const tooltip = await hoverUntilTooltip(wrapper, index, totalLabels)+ return createDefaultTooltipAccessor(tooltip)+ },+}diff --git a/frontend/src/test/insight-testing/render-data-visualization.tsx b/frontend/src/test/insight-testing/render-data-visualization.tsxnew file mode 100644index 000000000000..b08327a4c114--- /dev/null+++ b/frontend/src/test/insight-testing/render-data-visualization.tsx@@ -0,0 +1,88 @@+import { render } from '@testing-library/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { actionsModel } from '~/models/actionsModel'+import { groupsModel } from '~/models/groupsModel'+import { DataTableVisualization } from '~/queries/nodes/DataVisualization/DataVisualization'+import { DataVisualizationNode, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { QueryContext } from '~/queries/types'+import { ChartDisplayType } from '~/types'++import { initKeaTests } from '../init'++export const DATA_VIZ_TEST_KEY = 'sql-test-harness'++export const MONTHS = ['2025-10-01', '2025-11-01', '2025-12-01', '2026-01-01', '2026-02-01', '2026-03-01']+export const HOVER = 2++/** Minimal `[columnName, clickhouseType]` + row-major results — the same shape the+ * `/query` endpoint returns, distilled to what the chart selectors read. */+export interface DataVizFixture {+ columns: string[]+ types: [string, string][]+ results: unknown[][]+}++export function buildHogQLResponse({ columns, types, results }: DataVizFixture): HogQLQueryResponse {+ return {+ results,+ columns,+ types,+ hogql: '',+ hasMore: false,+ } as HogQLQueryResponse+}++export function buildDataVisualizationQuery(overrides?: Partial<DataVisualizationNode>): DataVisualizationNode {+ return {+ kind: NodeKind.DataVisualizationNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: 'SELECT month, pageviews FROM events GROUP BY month ORDER BY month',+ },+ display: ChartDisplayType.ActionsLineGraph,+ ...overrides,+ }+}++export interface RenderDataVisualizationProps {+ query?: DataVisualizationNode+ /** Row-major fixture, fed in via `cachedResults` to skip the network. */+ response: DataVizFixture+ /** Defaults to `{ 'product-analytics-quill-sql-charts': true }`; merge in more or override. */+ featureFlags?: Record<string, string | boolean>+ readOnly?: boolean+ embedded?: boolean+ context?: QueryContext<DataVisualizationNode>+}++/** Mount a SQL insight (`DataVisualizationNode`) the way the real scene does — through+ * `DataTableVisualization` → `dataVisualizationLogic` → `LineGraph` → the flag-gated quill+ * chart — with the query result injected via `cachedResults` so nothing hits the network. */+export function renderDataVisualization(props: RenderDataVisualizationProps): ReturnType<typeof render> {+ const featureFlags = { [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_SQL_CHARTS]: true, ...props.featureFlags }++ initKeaTests()+ actionsModel.mount()+ groupsModel.mount()++ const ffLogic = featureFlagLogic()+ ffLogic.mount()+ ffLogic.actions.setFeatureFlags(Object.keys(featureFlags), featureFlags)++ const cachedResults = buildHogQLResponse(props.response)++ return render(+ <DataTableVisualization+ uniqueKey={DATA_VIZ_TEST_KEY}+ query={props.query ?? buildDataVisualizationQuery()}+ setQuery={() => {}}+ cachedResults={cachedResults}+ context={props.context}+ readOnly={props.readOnly ?? true}+ embedded={props.embedded}+ />+ )+}diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 0e0dce8c69dc..a11804db7e0b 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -81,6 +81,13 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. `TimeSeriesBarChart`/`ComboChart` already render per-`yAxisId` axes but share one tick formatter across gutters.- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis.+## Testing++Import test helpers from `@posthog/quill-charts/testing` (jsdom-only).++- `getHogChart(scope?)` reads rendered overlays via stable `data-attr` hooks — `yTicks()`, `xTicks()`, `valueLabels()`, `referenceLines()`, axis titles, `seriesCount`, etc. Its `waitForTooltip()` returns a structured `TooltipSnapshot` but only when the chart was mounted via `renderHogChart` (it needs the captured tooltip context).+- For a chart rendered outside `renderHogChart` (e.g. a real product scene), read the tooltip from the DOM: `getHogChartTooltip()` / `waitForHogChartTooltip()` return the portal element; `createHogChartTooltip(el)` wraps it as `{ element, isPinned }`. If the chart renders the built-in `DefaultTooltip`, use `createDefaultTooltipAccessor(el)` for `label()`, `rows()`, `value(seriesLabel)`, `swatchColors()`, and `total()` — it reads `DefaultTooltip`'s `data-attr="hog-chart-tooltip-*"` hooks (a stable testing contract; keep the accessor and the component's attrs in sync).+## MaintenanceWhen adding or changing a chart, overlay, or config option, update this guide in the same PR and add a story next to the component.diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsxindex f7e4a427ba79..9956cbe51d6d 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx@@ -1,7 +1,7 @@import { cleanup, screen } from '@testing-library/react'import type { TooltipContext } from '../core/types'-import { makeOverlayContext, renderOverlayInChart } from '../testing'+import { createDefaultTooltipAccessor, makeOverlayContext, renderOverlayInChart } from '../testing'import { DefaultTooltip } from './DefaultTooltip'const SCALES = { x: () => 0, y: (v: number) => v, yTicks: () => [] }@@ -86,7 +86,11 @@ describe('DefaultTooltip', () => {it('falls back to valueFormatter for the total, applied with the first summable entry', () => {const metaSeries: TooltipContext['seriesData'] = [{ series: { key: 'usd', label: 'Revenue', data: [], meta: { unit: '$' } }, value: 10, color: '#000' },- { series: { key: 'usd2', label: 'Revenue 2', data: [], meta: { unit: '€' } }, value: 25, color: '#111' },+ {+ series: { key: 'usd2', label: 'Revenue 2', data: [], meta: { unit: '€' } },+ value: 25,+ color: '#111',+ },]renderTooltip({@@ -129,4 +133,36 @@ describe('DefaultTooltip', () => {expect(screen.queryByText('Total:')).toBeNull()})})++ describe('createDefaultTooltipAccessor', () => {+ it('reads the label, rows, values, swatch colors, and total', () => {+ const seriesData: TooltipContext['seriesData'] = [+ { series: { key: 'a', label: 'Revenue', data: [] }, value: 100, color: 'rgb(255, 0, 0)' },+ { series: { key: 'b', label: 'Cost', data: [] }, value: 40, color: 'rgb(0, 255, 0)' },+ ]+ renderTooltip({ showTotal: true, valueFormatter: (v) => `$${v}` }, seriesData)++ const tooltip = createDefaultTooltipAccessor(document.body)+ expect(tooltip.label()).toBe('When')+ expect(tooltip.rows()).toEqual(['Revenue', 'Cost'])+ expect(tooltip.value('Revenue')).toBe('$100')+ expect(tooltip.value('Cost')).toBe('$40')+ expect(tooltip.swatchColors()).toEqual(['rgb(255, 0, 0)', 'rgb(0, 255, 0)'])+ expect(tooltip.total()).toBe('$140')+ })++ it('returns undefined total when no total row is shown', () => {+ renderTooltip({})+ expect(createDefaultTooltipAccessor(document.body).total()).toBeUndefined()+ })++ it('includes overlay series in rows (rows is every rendered row, not summable-only)', () => {+ const seriesData: TooltipContext['seriesData'] = [+ { series: { key: 'a', label: 'Visits', data: [] }, value: 100, color: 'rgb(1, 2, 3)' },+ { series: { key: 'goal', label: 'Goal', data: [], overlay: true }, value: 30, color: 'rgb(4, 5, 6)' },+ ]+ renderTooltip({}, seriesData)+ expect(createDefaultTooltipAccessor(document.body).rows()).toEqual(['Visits', 'Goal'])+ })+ })})diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsxindex f1b886d9334b..6ef158258e37 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx@@ -36,19 +36,24 @@ export function DefaultTooltip<Meta = unknown>({return (<TooltipSurface>- <div className="font-semibold mb-1">{label}</div>+ <div data-attr="hog-chart-tooltip-label" className="font-semibold mb-1">+ {label}+ </div>{seriesData.map((s) => (- <div key={s.series.key} className="flex items-center gap-2">+ <div key={s.series.key} data-attr="hog-chart-tooltip-row" className="flex items-center gap-2"><TooltipSwatch color={s.color} />- <span>{s.series.label}:</span>- <strong>{format(s.value, s)}</strong>+ <span data-attr="hog-chart-tooltip-series">{s.series.label}:</span>+ <strong data-attr="hog-chart-tooltip-value">{format(s.value, s)}</strong></div>))}{renderTotal && (- <div className="flex items-center gap-2 mt-1 pt-1 border-t border-current/25 font-semibold">+ <div+ data-attr="hog-chart-tooltip-total"+ className="flex items-center gap-2 mt-1 pt-1 border-t border-current/25 font-semibold"+ ><span className="w-2" /><span>{totalLabel}:</span>- <strong>{formatTotal(total)}</strong>+ <strong data-attr="hog-chart-tooltip-value">{formatTotal(total)}</strong></div>)}</TooltipSurface>diff --git a/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx b/packages/quill/packages/charts/src/overlays/TooltipSurface.tsxindex 3b5a29dc2ce8..8ffee9008012 100644--- a/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx+++ b/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx@@ -49,6 +49,7 @@ export function TooltipSurface({export function TooltipSwatch({ color }: { color: string }): React.ReactElement {return (<span+ data-attr="hog-chart-tooltip-swatch"// eslint-disable-next-line react/forbid-dom-propsstyle={{display: 'inline-block',diff --git a/packages/quill/packages/charts/src/testing/index.ts b/packages/quill/packages/charts/src/testing/index.tsindex 101145e317d6..8724ca7dbac3 100644--- a/packages/quill/packages/charts/src/testing/index.ts+++ b/packages/quill/packages/charts/src/testing/index.ts@@ -7,9 +7,10 @@ export type { RenderHogChartOptions } from './render'export { makeOverlayContext, renderOverlayInChart } from './overlay'export type { OverlayContextOverrides } from './overlay'export {+ createDefaultTooltipAccessor,createHogChartTooltip,getHogChartTooltip,HOG_CHARTS_TOOLTIP_SELECTOR,waitForHogChartTooltip,} from './tooltip'-export type { HogChartTooltip } from './tooltip'+export type { DefaultTooltipAccessor, HogChartTooltip } from './tooltip'diff --git a/packages/quill/packages/charts/src/testing/tooltip.ts b/packages/quill/packages/charts/src/testing/tooltip.tsindex 9765d6945709..e7288a4b4128 100644--- a/packages/quill/packages/charts/src/testing/tooltip.ts+++ b/packages/quill/packages/charts/src/testing/tooltip.ts@@ -24,6 +24,53 @@ export function createHogChartTooltip(element: HTMLElement): HogChartTooltip {}}+/** Accessor for the built-in `DefaultTooltip` layout, reading its stable `data-attr`+ * test hooks. Use when a chart renders `DefaultTooltip` (directly or via a custom+ * `tooltip` render prop that wraps it). */+export interface DefaultTooltipAccessor extends HogChartTooltip {+ /** Header label — typically the hovered x-axis value. */+ label(): string+ /** Series labels in render order (excludes the total row). */+ rows(): string[]+ /** Formatted value for the series row whose label matches, or undefined. */+ value(seriesLabel: string): string | undefined+ /** Series swatch colors (inline `background-color`) in row order. */+ swatchColors(): string[]+ /** Formatted total-row value, or undefined when no total row is shown. */+ total(): string | undefined+}++const seriesLabelOf = (row: HTMLElement): string =>+ (row.querySelector('[data-attr="hog-chart-tooltip-series"]')?.textContent ?? '').replace(/:\s*$/, '').trim()++const swatchColorOf = (row: HTMLElement): string =>+ row.querySelector<HTMLElement>('[data-attr="hog-chart-tooltip-swatch"]')?.style.backgroundColor ?? ''++export function createDefaultTooltipAccessor(element: HTMLElement): DefaultTooltipAccessor {+ const rowEls = (): HTMLElement[] =>+ Array.from(element.querySelectorAll<HTMLElement>('[data-attr="hog-chart-tooltip-row"]'))++ return Object.assign(createHogChartTooltip(element), {+ label(): string {+ return element.querySelector('[data-attr="hog-chart-tooltip-label"]')?.textContent?.trim() ?? ''+ },+ rows(): string[] {+ return rowEls().map(seriesLabelOf)+ },+ value(seriesLabel: string): string | undefined {+ const row = rowEls().find((r) => seriesLabelOf(r) === seriesLabel)+ return row?.querySelector('[data-attr="hog-chart-tooltip-value"]')?.textContent ?? undefined+ },+ swatchColors(): string[] {+ return rowEls().map(swatchColorOf)+ },+ total(): string | undefined {+ const total = element.querySelector('[data-attr="hog-chart-tooltip-total"]')+ return total?.querySelector('[data-attr="hog-chart-tooltip-value"]')?.textContent ?? undefined+ },+ })+}+/** Currently rendered chart tooltip element, or null if none is mounted. */export function getHogChartTooltip(): HTMLElement | null {return document.querySelector(HOG_CHARTS_TOOLTIP_SELECTOR)