: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(product-analytics): speed up and consolidate insight chart test suites (#68776)
Sam Penningtone73fcd45d6bc
diff --git a/frontend/src/test/insight-testing/README.md b/frontend/src/test/insight-testing/README.mdindex c63503416bca..9f5b91f4149f 100644--- a/frontend/src/test/insight-testing/README.md+++ b/frontend/src/test/insight-testing/README.md@@ -25,10 +25,13 @@ Handles all setup automatically — Kea context, common logics, and API mocks.| Prop | Type | Description || --------------- | ------------------- | -------------------------------------------------------- || `query` | `TrendsQuery` | Query to render (defaults to a `$pageview` trends query) |-| `showFilters` | `boolean` | Show filter controls (defaults to `true`) |+| `showFilters` | `boolean` | Show filter controls (defaults to `false`) || `mocks` | `SetupMocksOptions` | Override event/property definitions and property values || `mockResponses` | `MockResponse[]` | Custom query response matchers |+By default only the chart renders — no filter editor UI.+Mounting the filter controls roughly doubles a test's runtime, so use `renderInsightPage` (same props, `showFilters` defaults to `true`) only when the test interacts with them.+## `renderWithInsights(props)`Renders any component with insight mocks and Kea logics ready.@@ -95,7 +98,7 @@ without waiting.## Interactions-Filter controls render by default (`showFilters` defaults to `true`):+Filter interactions need the filter controls mounted — render with `renderInsightPage` (or pass `showFilters: true`):```tsximport { series, breakdown, interval, display, compare } from './index'diff --git a/frontend/src/test/insight-testing/index.ts b/frontend/src/test/insight-testing/index.tsindex 09d62c2f3e55..0f28fe3c1c9f 100644--- a/frontend/src/test/insight-testing/index.ts+++ b/frontend/src/test/insight-testing/index.ts@@ -9,7 +9,7 @@ export {buildStickinessQuery,buildTrendsQuery,renderInsight,- renderInsight as renderInsightPage,+ renderInsightPage,renderWithInsights,} from './render-insight'export type { InsightQuery, RenderInsightProps, RenderWithInsightsProps } from './render-insight'diff --git a/frontend/src/test/insight-testing/interactions.ts b/frontend/src/test/insight-testing/interactions.tsindex 446fdd26204b..9736306dd4b7 100644--- a/frontend/src/test/insight-testing/interactions.ts+++ b/frontend/src/test/insight-testing/interactions.ts@@ -150,13 +150,13 @@ export const chart = {index: number,totalLabels = trendsSeries.pageviews.labels.length): Promise<InsightTooltipAccessor> {- const canvas = await screen.findByRole('img', { name: /chart with/i }, { timeout: DEBOUNCE_TIMEOUT })+ const canvas = await screen.findByLabelText(/chart with/i, {}, { timeout: DEBOUNCE_TIMEOUT })const wrapper = canvas.parentElement!const tooltip = await hoverUntilTooltip(wrapper, index, totalLabels)return createInsightTooltipAccessor(tooltip)},async clickAtIndex(index: number, totalLabels = trendsSeries.pageviews.labels.length): Promise<void> {- const canvas = await screen.findByRole('img', { name: /chart with/i }, { timeout: DEBOUNCE_TIMEOUT })+ const canvas = await screen.findByLabelText(/chart with/i, {}, { timeout: DEBOUNCE_TIMEOUT })const wrapper = canvas.parentElement!await clickAtIndex(wrapper, index, totalLabels)},@@ -175,7 +175,7 @@ export const chart = {* `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 canvas = await screen.findByLabelText(/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-insight.tsx b/frontend/src/test/insight-testing/render-insight.tsxindex 4cbd77971aae..2e2dd25ae69e 100644--- a/frontend/src/test/insight-testing/render-insight.tsx+++ b/frontend/src/test/insight-testing/render-insight.tsx@@ -134,10 +134,18 @@ export function renderInsight(props: RenderInsightProps = {}): ReturnType<typeofreturn render(<InsightWrapperquery={props.query ?? buildTrendsQuery()}- showFilters={props.showFilters ?? true}+ showFilters={props.showFilters ?? false}context={props.context}inSharedMode={props.inSharedMode}embedded={props.embedded}/>)}++/** Render the full insight page including the filter editor UI (header, series+ * editor, breakdown, display config). Mounting all of that roughly doubles a+ * test's runtime versus the chart-only `renderInsight`, so reach for this only+ * when the test interacts with the filter controls themselves. */+export function renderInsightPage(props: RenderInsightProps = {}): ReturnType<typeof render> {+ return renderInsight({ ...props, showFilters: props.showFilters ?? true })+}diff --git a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.test.tsx b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.test.tsxindex 8263c848509c..15041c019c45 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.test.tsx@@ -31,7 +31,7 @@ describe('FunnelLineChart', () => {expect(tooltip.element.textContent).toContain('40%')})- it('renders a series per breakdown variant', async () => {+ it('renders a series per breakdown variant with the breakdown label on each tooltip row', async () => {renderInsight({query: buildFunnelsQuery({breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },@@ -41,14 +41,6 @@ describe('FunnelLineChart', () => {await waitFor(() => {expect(getHogChart().seriesCount).toBe(2)})- })-- it('shows the breakdown label on each tooltip row when broken down', async () => {- renderInsight({- query: buildFunnelsQuery({- breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },- }),- })await chart.clickAtIndex(2)const tooltip = await waitForHogChartTooltip()@@ -74,8 +66,6 @@ describe('FunnelLineChart', () => {})describe('orders breakdown rows by descending conversion value', () => {- // Captured once from a single render; the assertions only read these strings, so the- // per-test cleanup() between it.each cases doesn't matter.let orderedRows: { label: string; value: string | undefined }[]beforeAll(async () => {@@ -91,13 +81,12 @@ describe('FunnelLineChart', () => {// The query returns Safari, Chrome, Firefox, but at index 2 the conversion values are// Firefox=60%, Safari=40%, Chrome=20%, so rows must be re-ordered by descending value.- it.each([- { position: 0, browser: 'Firefox', pct: '60%' },- { position: 1, browser: 'Safari', pct: '40%' },- { position: 2, browser: 'Chrome', pct: '20%' },- ])('row $position is $browser ($pct)', ({ position, browser, pct }) => {- expect(orderedRows[position].label).toContain(browser)- expect(orderedRows[position].value).toContain(pct)+ it('sorts rows Firefox (60%), Safari (40%), Chrome (20%)', () => {+ expect(orderedRows).toEqual([+ { label: expect.stringContaining('Firefox'), value: expect.stringContaining('60%') },+ { label: expect.stringContaining('Safari'), value: expect.stringContaining('40%') },+ { label: expect.stringContaining('Chrome'), value: expect.stringContaining('20%') },+ ])})})@@ -167,49 +156,6 @@ describe('FunnelLineChart', () => {})})- describe('goal lines', () => {- it('renders configured goal lines on the chart', async () => {- renderInsight({- query: buildFunnelsQuery({- funnelsFilter: { goalLines: [{ label: 'Target', value: 30, displayIfCrossed: true }] },- }),- })-- await screen.findByLabelText(/chart with/i)- await waitFor(() => {- const lines = getHogChart().referenceLines()- // value→pixel isn't recoverable from the DOM; assert the line is labelled,- // drawn horizontally (across the value axis), and actually positioned.- expect(lines).toEqual([- expect.objectContaining({- label: 'Target',- orientation: 'horizontal',- position: expect.any(Number),- }),- ])- })- })- })-- describe('trend lines overlay', () => {- it('adds a trend-line overlay when showTrendLines is enabled', async () => {- renderInsight({- query: buildFunnelsQuery({ funnelsFilter: { showTrendLines: true, showValuesOnSeries: true } }),- })-- // main series + trend-line series = 2 rendered series- await waitFor(() => {- expect(getHogChart().seriesCount).toBe(2)- })-- // the trend line is an overlay — excluded from value labels, so the 5 data- // points yield 5 labels, not 10 (a regular 2nd series would double them)- await waitFor(() => {- expect(getHogChart().valueLabels()).toHaveLength(5)- })- })- })-describe('legend', () => {it('shows a legend item per breakdown series when showLegend is enabled', async () => {renderInsight({@@ -270,37 +216,6 @@ describe('FunnelLineChart', () => {})describe('annotations', () => {- it.each([- { inSharedMode: false, expectsBadges: true },- { inSharedMode: true, expectsBadges: false },- ])(- 'renders annotation badges only when inSharedMode is false (inSharedMode=$inSharedMode)',- async ({ inSharedMode, expectsBadges }) => {- renderInsight({- query: buildFunnelsQuery(),- inSharedMode,- mocks: {- annotations: [- buildAnnotation({- scope: AnnotationScope.Project,- content: 'Hedgehog spotted',- date_marker: '2024-06-12T12:00:00Z',- }),- ],- },- })-- if (expectsBadges) {- await waitFor(() => {- expect(document.querySelectorAll('.AnnotationsBadge').length).toBeGreaterThan(0)- })- } else {- await screen.findByLabelText(/chart with/i)- expect(document.querySelectorAll('.AnnotationsBadge')).toHaveLength(0)- }- }- )-it.each([{ showAnnotations: undefined, expectsBadges: true },{ showAnnotations: true, expectsBadges: true },diff --git a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/funnelChartTransforms.test.ts b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/funnelChartTransforms.test.tsindex 267692f32c0e..e986a634c4f6 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/funnelChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/funnelChartTransforms.test.ts@@ -1,5 +1,3 @@-import type { FunnelStepWithNestedBreakdown } from '~/types'-import { buildFunnelLineSeries, buildFunnelLineTimeSeriesConfig, type IndexedFunnelStep } from './funnelChartTransforms'const RED = '#ff0000'@@ -170,12 +168,4 @@ describe('funnelChartTransforms', () => {expect(config.trendLines).toBeUndefined()})})-- describe('type contracts', () => {- it('IndexedFunnelStep is assignable from FunnelStepWithNestedBreakdown', () => {- const step: FunnelStepWithNestedBreakdown = makeStep()- const indexed: IndexedFunnelStep = { ...step, id: 0, seriesIndex: 0, colorIndex: 0 }- expect(indexed.id).toBe(0)- })- })})diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.compare.test.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.compare.test.tsxdeleted file mode 100644index d696568a2b2d..000000000000--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.compare.test.tsx+++ /dev/null@@ -1,72 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, waitFor } from '@testing-library/react'--import type { Series } from '@posthog/quill-charts'-import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'--import { buildStickinessQuery, renderInsight } from '~/test/insight-testing'-import { ChartDisplayType } from '~/types'--import type { TrendsSeriesMeta } from '../../trends/shared/trendsSeriesMeta'--// Capture the series the component hands to the quill bar chart so we can assert the resolved-// colors end-to-end (indexedResults → getTrendsColor → dimming) without poking at the canvas.-const mockCapturedSeries: Series<TrendsSeriesMeta>[][] = []-jest.mock('@posthog/quill-charts', () => {- const actual = jest.requireActual('@posthog/quill-charts')- return {- __esModule: true,- ...actual,- TimeSeriesBarChart: (props: { series: Series<TrendsSeriesMeta>[] }) => {- mockCapturedSeries.push(props.series)- return null- },- }-})--let cleanupJsdom: () => void-let cleanupRaf: () => void--beforeEach(() => {- mockCapturedSeries.length = 0- cleanupJsdom = setupJsdom()- cleanupRaf = setupSyncRaf()-})--afterEach(() => {- cleanupRaf()- cleanupJsdom()- cleanup()-})--describe('StickinessBarChart compare-against-previous', () => {- it('dims the previous-period series to 0.5 alpha while the current period keeps its full color', async () => {- renderInsight({- query: buildStickinessQuery({- stickinessFilter: { display: ChartDisplayType.ActionsBar },- compareFilter: { compare: true },- }),- })-- await waitFor(- () => {- const latest = mockCapturedSeries[mockCapturedSeries.length - 1] ?? []- if (!latest.some((s) => s.meta?.compare_label === 'previous')) {- throw new Error('compare series not captured yet')- }- },- { timeout: 5000 }- )-- const series = mockCapturedSeries[mockCapturedSeries.length - 1]- const previous = series.find((s) => s.meta?.compare_label === 'previous')- const current = series.find((s) => s.meta?.compare_label === 'current')-- expect(previous).not.toBeUndefined()- expect(current).not.toBeUndefined()- // Previous period is dimmed via rgba(...) at half opacity; current keeps the opaque palette color.- expect(previous!.color).toMatch(/^rgba\(.+,\s*0?\.5\)$/)- expect(current!.color).not.toMatch(/^rgba\(/)- })-})diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.test.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.test.tsxindex efb6f58e04c0..899e1fd9c011 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.test.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.test.tsx@@ -7,7 +7,7 @@ import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'import { FEATURE_FLAGS } from 'lib/constants'import { NodeKind } from '~/queries/schema/schema-general'-import { buildStickinessQuery, chart, getHogChart, personsModal, renderInsight } from '~/test/insight-testing'+import { buildStickinessQuery, chart, personsModal, renderInsight } from '~/test/insight-testing'import { ChartDisplayType } from '~/types'configure({ asyncUtilTimeout: 3000 })@@ -34,57 +34,31 @@ describe('StickinessBarChart', () => {it.each([{ display: ChartDisplayType.ActionsBar, layout: 'stacked' },{ display: ChartDisplayType.ActionsUnstackedBar, layout: 'grouped' },- ])('renders a $layout bar chart from a StickinessQuery', async ({ display }) => {- renderInsight({- query: stickinessBar({ stickinessFilter: { display } }),- })-- await waitFor(- () => {- expect(screen.getByTestId('stickiness-bar-graph')).toBeInTheDocument()- },- { timeout: 5000 }- )- })-- it('renders one series per event', async () => {+ ])('renders a $layout bar chart from a StickinessQuery with one series per event', async ({ display }) => {renderInsight({query: stickinessBar({series: [{ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },],+ stickinessFilter: { display },}),})await waitFor(() => {+ expect(screen.getByTestId('stickiness-bar-graph')).toBeInTheDocument()expect(screen.getByLabelText(/chart with 2 data series/i)).toBeInTheDocument()},{ timeout: 5000 })})- it('y-axis: renders percent ticks (legacy `${value.toFixed(1)}%` parity)', async () => {- renderInsight({ query: stickinessBar() })-- await screen.findByLabelText(/chart with/i)- await waitFor(() => {- const ticks = getHogChart().yTicks()- expect(ticks.length).toBeGreaterThan(0)- expect(ticks.every((t) => /%/.test(t))).toBe(true)- })- })-- it('tooltip: percent value + "Stickiness on {interval} {day}" title (not a calendar date)', async () => {+ it('tooltip: formats series values as percentages of the series total', async () => {renderInsight({ query: stickinessBar() })const tooltip = await chart.hoverTooltip(2)- // Days are 1-indexed in the mock, so bucket 2 == day 3.expect(tooltip.row('Pageview')).toMatch(/%/)- expect(tooltip.title()).toMatch(/Stickiness on day 3/)- // Must NOT default to a Unix-epoch-derived calendar date.- expect(tooltip.title()).not.toMatch(/1970/i)})it('renders InsightEmptyState when all series are zero', async () => {@@ -119,26 +93,6 @@ describe('StickinessBarChart', () => {expect(personsModal.title()).toMatch(/Pageview/)})- it('click → context.onDataPointClick fires with the integer day instead of opening the modal', async () => {- const onDataPointClick = jest.fn()- renderInsight({- query: stickinessBar(),- context: { onDataPointClick },- })-- await chart.clickAtIndex(2)-- await waitFor(- () => {- expect(onDataPointClick).toHaveBeenCalledTimes(1)- },- { timeout: 5000 }- )- const [seriesArg] = onDataPointClick.mock.calls[0]- expect(seriesArg.day).toBe(3)- expect(personsModal.get()).not.toBeInTheDocument()- })-describe('quill in-chart legend (PRODUCT_ANALYTICS_QUILL_LEGEND on)', () => {const quillLegendFlag = { [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]: true }const twoSeriesBar = stickinessBar({diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.test.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.test.tsxindex e7d5c4dab3ce..58b10cb58565 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.test.tsx@@ -8,7 +8,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { ExportType } from '~/exporter/types'import { NodeKind } from '~/queries/schema/schema-general'-import { buildStickinessQuery, chart, getHogChart, personsModal, renderInsight } from '~/test/insight-testing'+import { buildStickinessQuery, chart, personsModal, renderInsight } from '~/test/insight-testing'configure({ asyncUtilTimeout: 5000 })// With asyncUtilTimeout at 5s, a single legitimate waitFor can exhaust Jest's default@@ -39,21 +39,6 @@ describe('StickinessLineChart', () => {})})- describe('y-axis', () => {- it('renders percent ticks (legacy `${value.toFixed(1)}%` parity)', async () => {- renderInsight({ query: buildStickinessQuery() })-- await screen.findByLabelText(/chart with/i)- await waitFor(() => {- const ticks = getHogChart().yTicks()- expect(ticks.length).toBeGreaterThan(0)- for (const t of ticks) {- expect(t).toMatch(/%/)- }- })- })- })-describe('tooltips', () => {it('formats series values as percentages of the series total', async () => {renderInsight({ query: buildStickinessQuery() })@@ -62,16 +47,6 @@ describe('StickinessLineChart', () => {// Pageview canned series is [45, 82, 134, 210, 95], total 566, so bucket 2 == 134/566 ≈ 23.7%.expect(tooltip.row('Pageview')).toMatch(/%/)})-- it('uses "Stickiness on {interval} {day}" as the tooltip title (not a calendar date)', async () => {- renderInsight({ query: buildStickinessQuery() })-- const tooltip = await chart.hoverTooltip(2)- // Day at index 2 is 3 in the mock's 1-indexed stickiness days.- expect(tooltip.title()).toMatch(/Stickiness on day 3/)- // Critically — must NOT default to a Unix-epoch-derived calendar date.- expect(tooltip.title()).not.toMatch(/1970/i)- })})describe('empty state', () => {@@ -104,23 +79,6 @@ describe('StickinessLineChart', () => {expect(personsModal.title()).toMatch(/Pageview/)})- it('fires context.onDataPointClick with the integer day instead of opening the modal', async () => {- const onDataPointClick = jest.fn()- renderInsight({- query: buildStickinessQuery(),- context: { onDataPointClick },- })-- await chart.clickAtIndex(2)-- await waitFor(() => {- expect(onDataPointClick).toHaveBeenCalledTimes(1)- })- const [seriesArg] = onDataPointClick.mock.calls[0]- expect(seriesArg.day).toBe(3)- expect(personsModal.get()).not.toBeInTheDocument()- })-describe('shared mode', () => {beforeEach(() => {// Shared/exported pages set this global before React mounts; trendsDataLogic.hasPersonsModal reads it.diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.tsindex e2671f4592ce..b2bf18bfe191 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts@@ -2,6 +2,7 @@ import { DEFAULT_Y_AXIS_ID } from '@posthog/quill-charts'import type { TooltipConfig, YAxisConfig } from '@posthog/quill-charts'import { hexToRGBA } from 'lib/utils/colors'+import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'import { ChartDisplayType } from '~/types'@@ -10,6 +11,7 @@ import {buildStickinessLineTimeSeriesConfig,buildStickinessMainSeries,buildStickinessSeries,+ buildStickinessTooltipTitle,stickinessPercentFormatter,toPercentData,type StickinessResultLike,@@ -194,6 +196,28 @@ describe('stickinessChartTransforms', () => {})})+ describe('buildStickinessTooltipTitle', () => {+ const makeDatum = (date_label?: string): SeriesDatum => ({+ id: 0,+ dataIndex: 0,+ datasetIndex: 0,+ order: 0,+ count: 0,+ date_label,+ })++ it.each<[string, string | null | undefined, SeriesDatum[], string]>([+ ['passes the integer day through for a day interval', 'day', [makeDatum('3')], 'Stickiness on day 3'],+ ['uses the query interval when set', 'week', [makeDatum('2')], 'Stickiness on week 2'],+ ['defaults the interval to "day" when null', null, [makeDatum('3')], 'Stickiness on day 3'],+ ['defaults the interval to "day" when undefined', undefined, [makeDatum('3')], 'Stickiness on day 3'],+ ['renders an empty day when date_label is missing', 'day', [makeDatum(undefined)], 'Stickiness on day '],+ ['renders an empty day when seriesData is empty', 'day', [], 'Stickiness on day '],+ ])('%s', (_, interval, seriesData, expected) => {+ expect(buildStickinessTooltipTitle(interval)(seriesData)).toBe(expected)+ })+ })+describe('buildStickinessLineTimeSeriesConfig', () => {const TOOLTIP: TooltipConfig = { pinnable: true, placement: 'top' }diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsxindex df6ad614111a..6bf479181e8c 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx@@ -68,12 +68,13 @@ describe('TrendsBarChart (ActionsBar)', () => {)})- it('shows the series value in the tooltip on hover', async () => {+ it('shows the series value and a date header in the tooltip on hover', async () => {renderInsight({ query: trendsBar() })await screen.findByLabelText(/chart with/i, undefined, { timeout: 5000 })const tooltip = await chart.hoverTooltip(2)expect(tooltip.row('Pageview')).toContain('134')+ expect(tooltip.title()).toMatch(/Jun/)})it('stacked tooltip shows each series own value, not the cumulative stack total', async () => {@@ -104,14 +105,6 @@ describe('TrendsBarChart (ActionsBar)', () => {expect(tooltip.row('Napped')).not.toContain('139')})- it('shows a date header in the tooltip', async () => {- renderInsight({ query: trendsBar() })- await screen.findByLabelText(/chart with/i, undefined, { timeout: 5000 })-- const tooltip = await chart.hoverTooltip(2)- expect(tooltip.title()).toMatch(/Jun/)- })-it('opens the persons modal on click for a single series', async () => {renderInsight({ query: trendsBar() })await screen.findByLabelText(/chart with/i, undefined, { timeout: 5000 })@@ -148,27 +141,31 @@ describe('TrendsBarChart (ActionsBar)', () => {})})- it('renders InsightEmptyState when all series are zero', async () => {- renderInsight({- query: trendsBar({- series: [- {- kind: NodeKind.EventsNode,- event: 'NoActivity',- name: 'NoActivity',- },- ],- }),- })+ it.each([ChartDisplayType.ActionsBar, ChartDisplayType.ActionsBarValue])(+ 'renders InsightEmptyState when all values are zero for %s',+ async (display) => {+ renderInsight({+ query: buildTrendsQuery({+ trendsFilter: { display },+ series: [+ {+ kind: NodeKind.EventsNode,+ event: 'NoActivity',+ name: 'NoActivity',+ },+ ],+ }),+ })- await waitFor(- () => {- expect(screen.getByTestId('insight-empty-state')).toBeInTheDocument()- },- { timeout: 5000 }- )- expect(screen.queryByLabelText(/chart with/i)).not.toBeInTheDocument()- })+ await waitFor(+ () => {+ expect(screen.getByTestId('insight-empty-state')).toBeInTheDocument()+ },+ { timeout: 5000 }+ )+ expect(screen.queryByLabelText(/chart with/i)).not.toBeInTheDocument()+ }+ )it('shows current and previous period rows in compare mode', async () => {renderInsight({@@ -224,19 +221,6 @@ describe('TrendsBarChart (ActionsBarValue)', () => {...extra,})- it('renders without crashing for a single event', async () => {- renderInsight({- query: aggregatedBar(),- })-- await waitFor(- () => {- expect(screen.getByLabelText(/chart with/i)).toBeInTheDocument()- },- { timeout: 5000 }- )- })-it('renders custom axis titles in horizontal aggregated mode', async () => {renderInsight({query: aggregatedBar({@@ -258,28 +242,42 @@ describe('TrendsBarChart (ActionsBarValue)', () => {).toContain('rotate(-90')})- it('emits one series with a colored bar per breakdown value', async () => {+ // Five hedgehog breakdowns → by default one series carrying five per-bar colors across five+ // bands, labeled by breakdown value; with stackBreakdownValues they collapse onto one band.+ it.each([+ {+ name: 'one band per breakdown value, labeled by breakdown value, by default',+ stackBreakdownValues: undefined,+ expectedSeries: 1,+ expectedTicks: 5,+ containsTick: 'Spike',+ },+ {+ name: 'collapses breakdown bars onto one band when stackBreakdownValues is set',+ stackBreakdownValues: true,+ expectedSeries: 5,+ expectedTicks: 1,+ containsTick: undefined,+ },+ ])('$name', async ({ stackBreakdownValues, expectedSeries, expectedTicks, containsTick }) => {renderInsight({query: aggregatedBar({- series: [- {- kind: NodeKind.EventsNode,- event: 'Napped',- name: 'Napped',- },- ],- breakdownFilter: {- breakdown: 'hedgehog',- breakdown_type: 'event',- },+ series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },+ trendsFilter: { display: ChartDisplayType.ActionsBarValue, stackBreakdownValues },}),})+ await screen.findByLabelText(new RegExp(`chart with ${expectedSeries} data series`, 'i'), undefined, {+ timeout: 5000,+ })- // Five hedgehog breakdowns → one series carrying five per-bar colors across five bands.- await screen.findByLabelText(/chart with 1 data series/i, undefined, { timeout: 5000 })await waitFor(() => {- expect(getHogChart().yTicks()).toHaveLength(5)+ const ticks = getHogChart().yTicks()+ expect(ticks).toHaveLength(expectedTicks)+ if (containsTick) {+ expect(ticks).toEqual(expect.arrayContaining([containsTick]))+ }},{ timeout: 5000 })@@ -309,43 +307,6 @@ describe('TrendsBarChart (ActionsBarValue)', () => {expect(new Set(pillColors).size).toBeGreaterThan(1)})- it('labels each aggregated breakdown bar by its breakdown value, one band per value by default', async () => {- renderInsight({- query: aggregatedBar({- series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],- breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },- }),- })- await screen.findByLabelText(/chart with 1 data series/i, undefined, { timeout: 5000 })-- await waitFor(- () => {- const ticks = getHogChart().yTicks()- expect(ticks).toEqual(expect.arrayContaining(['Spike']))- expect(ticks).toHaveLength(5)- },- { timeout: 5000 }- )- })-- it('collapses breakdown bars onto one band when stackBreakdownValues is set', async () => {- renderInsight({- query: aggregatedBar({- series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],- breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },- trendsFilter: { display: ChartDisplayType.ActionsBarValue, stackBreakdownValues: true },- }),- })- await screen.findByLabelText(/chart with 5 data series/i, undefined, { timeout: 5000 })-- await waitFor(- () => {- expect(getHogChart().yTicks()).toHaveLength(1)- },- { timeout: 5000 }- )- })-// A dashboard/card tile is a fixed height, so the chart caps the breakdown rows to those that// fit. The full insight page is `embedded: false` — even when opened from a dashboard, where// `dashboardId` is in the URL — so it must keep growing to render every breakdown row.@@ -424,22 +385,6 @@ describe('TrendsBarChart (ActionsBarValue)', () => {expect(personsModal.title()).not.toMatch(/Wednesday/)})- it('opens the persons modal on click in compare mode instead of pinning the tooltip', async () => {- renderInsight({- query: aggregatedBar({ compareFilter: { compare: true } }),- })- await screen.findByLabelText(/chart with/i, undefined, { timeout: 5000 })-- await chart.clickAtIndex(0)-- await waitFor(- () => {- expect(personsModal.get()).toBeInTheDocument()- },- { timeout: 5000 }- )- })-it('fires context.onDataPointClick without a day argument', async () => {// Per-band breakdown resolution is covered at the unit-handler level — the// hog-charts hover/click helpers don't yet handle horizontal axis-orientation, so@@ -489,27 +434,6 @@ describe('TrendsBarChart (ActionsBarValue)', () => {expect(rowText).toContain('11')})- it('renders InsightEmptyState when every aggregated_value is zero', async () => {- renderInsight({- query: aggregatedBar({- series: [- {- kind: NodeKind.EventsNode,- event: 'NoActivity',- name: 'NoActivity',- },- ],- }),- })-- await waitFor(- () => {- expect(screen.getByTestId('insight-empty-state')).toBeInTheDocument()- },- { timeout: 5000 }- )- })-it('keeps the previous-period identifier glyph opaque while dimming only the row ribbon', async () => {// Give the previous period the larger aggregated_value so it sorts topmost (DESC) and is the// bar hovered at plotTop. Its series color arrives pre-dimmed (rgba .5); the ribbon should keep@@ -582,17 +506,6 @@ describe('TrendsBarChart (ActionsUnstackedBar)', () => {...extra,})- it('routes grouped bar insights through the hog-charts adapter', async () => {- renderInsight({ query: groupedBar() })-- await waitFor(- () => {- expect(screen.getByTestId('trend-bar-graph')).toBeInTheDocument()- },- { timeout: 5000 }- )- })-it('renders one band per series in grouped layout', async () => {renderInsight({query: groupedBar({diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.tsindex b80dcab532cc..aef9da40aa6d 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts@@ -386,21 +386,6 @@ describe('buildTrendsBarChartModel', () => {expect(model.config.barLayout).toBe('stacked')})- it.each([- { isGrouped: false, isPercentStackView: false, expected: 'stacked' },- { isGrouped: true, isPercentStackView: false, expected: 'grouped' },- { isGrouped: false, isPercentStackView: true, expected: 'percent' },- { isGrouped: true, isPercentStackView: true, expected: 'percent' },- ])('maps layout flags to barLayout=$expected', ({ isGrouped, isPercentStackView, expected }) => {- const model = buildTrendsBarChartModel(results, {- getColor: () => RED,- labels: [],- isGrouped,- isPercentStackView,- })- expect(model.config.barLayout).toBe(expected)- })-it('forwards an x-axis tick formatter into the config', () => {const model = buildTrendsBarChartModel(results, {getColor: () => RED,diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsxindex 57c84228b88f..9d2c3eeb88d4 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsx@@ -92,16 +92,7 @@ describe('TrendsLifecycleChart', () => {expect(tooltip.row('Returning')).toBeTruthy()expect(tooltip.row('Resurrecting')).toBeTruthy()expect(tooltip.row('Dormant')).toBeTruthy()- })-- it('uses "Users" as the group type label in the tooltip', async () => {- renderInsight({- query: buildLifecycleQuery() as unknown as InsightQuery,- mocks: { additionalMockResponses: lifecycleMocks },- })-- await screen.findByTestId('trend-lifecycle-graph')- const tooltip = await chart.hoverTooltip(2)+ // "Users" is the group type label.expect(tooltip.element.textContent).toMatch(/Users/)})@@ -133,26 +124,33 @@ describe('TrendsLifecycleChart', () => {)})- it('renders the legend items in the same order as the rendered series', async () => {+ // Status order must match buildTrendsLifecycleSeries' sort: dormant → returning → resurrecting → new.+ it.each([+ {+ name: 'renders the legend items in series order when showLegend is set',+ showLegend: true,+ expectedLabels: ['Dormant', 'Returning', 'Resurrecting', 'New'],+ },+ {+ name: 'omits the legend when showLegend is not set',+ showLegend: undefined,+ expectedLabels: null,+ },+ ])('$name', async ({ showLegend, expectedLabels }) => {renderInsight({- query: buildLifecycleQuery({ lifecycleFilter: { showLegend: true } }) as unknown as InsightQuery,- mocks: { additionalMockResponses: lifecycleMocks },- })-- await screen.findByTestId('trend-lifecycle-graph')- // Status order must match buildTrendsLifecycleSeries' sort: dormant → returning → resurrecting → new.- const legend = await screen.findByTestId('hog-chart-timeseries-bar-legend')- const labels = Array.from(legend.children).map((el) => el.textContent?.trim())- expect(labels).toEqual(['Dormant', 'Returning', 'Resurrecting', 'New'])- })-- it('omits the legend when showLegend is not set', async () => {- renderInsight({- query: buildLifecycleQuery() as unknown as InsightQuery,+ query: buildLifecycleQuery(+ showLegend ? { lifecycleFilter: { showLegend } } : {}+ ) as unknown as InsightQuery,mocks: { additionalMockResponses: lifecycleMocks },})await screen.findByTestId('trend-lifecycle-graph')- expect(screen.queryByTestId('hog-chart-timeseries-bar-legend')).not.toBeInTheDocument()+ if (expectedLabels) {+ const legend = await screen.findByTestId('hog-chart-timeseries-bar-legend')+ const labels = Array.from(legend.children).map((el) => el.textContent?.trim())+ expect(labels).toEqual(expectedLabels)+ } else {+ expect(screen.queryByTestId('hog-chart-timeseries-bar-legend')).not.toBeInTheDocument()+ }})})diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsxindex d5234a2ca747..0168a57fdbb0 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { cleanup, configure, fireEvent, screen, waitFor } from '@testing-library/react'+import { cleanup, configure, screen, waitFor } from '@testing-library/react'import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'@@ -44,14 +44,6 @@ afterEach(() => {describe('TrendsLineChart', () => {describe('tooltips', () => {- it('shows the series value for a single series', async () => {- renderInsight({ query: buildTrendsQuery() })-- const tooltip = await chart.hoverTooltip(2)-- expect(tooltip.row('Pageview')).toContain('134')- })-it('shows each series with its own value for multiple series', async () => {renderInsight({query: buildTrendsQuery({@@ -197,37 +189,9 @@ describe('TrendsLineChart', () => {expect(tooltip.row('ActiveSeries')).toContain('3')expect(tooltip.row('EmptySeries')).toContain('0')})-- it('renders correctly when series has no action metadata', async () => {- renderInsight({- query: buildTrendsQuery({- series: [{ kind: NodeKind.EventsNode, event: 'Minimal', name: 'Minimal' }],- }),- })-- const tooltip = await chart.hoverTooltip(0)-- expect(tooltip.row('Minimal')).toContain('1')- })})describe('moving average overlay', () => {- it('adds a dashed moving-average series per result when enabled', async () => {- renderInsight({- query: buildTrendsQuery({- trendsFilter: {- showMovingAverage: true,- movingAverageIntervals: 3,- },- }),- })-- // One data series + one moving-average overlay = 2 rendered series.- await waitFor(() => {- expect(screen.getByLabelText(/chart with 2 data series/i)).toBeInTheDocument()- })- })-it('omits the moving-average series from tooltip rows', async () => {renderInsight({query: buildTrendsQuery({@@ -310,30 +274,6 @@ describe('TrendsLineChart', () => {expect(screen.getByLabelText(/chart with 2 data series/i)).toBeInTheDocument()})})-- it('uses percent ticks on the y-axis in percent stack view', async () => {- renderInsight({- query: buildTrendsQuery({- series: [- { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },- { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },- ],- trendsFilter: {- display: ChartDisplayType.ActionsAreaGraph,- showPercentStackView: true,- },- }),- })-- await screen.findByLabelText(/chart with/i)- await waitFor(() => {- const ticks = getHogChart().yTicks()- expect(ticks.length).toBeGreaterThan(0)- for (const t of ticks) {- expect(t).toMatch(/%/)- }- })- })})describe('tooltip date title', () => {@@ -350,44 +290,6 @@ describe('TrendsLineChart', () => {})})- describe('tooltip pin lifecycle', () => {- it.each([- {- trigger: 'Escape key press',- unpin: async () => {- fireEvent.keyDown(document, { key: 'Escape' })- },- },- {- trigger: 'click outside the chart',- unpin: async () => {- // The chart attaches its outside-click listener via setTimeout(0); flush- // first so the listener actually intercepts the click.- await new Promise((resolve) => setTimeout(resolve, 5))- const outside = document.body.appendChild(document.createElement('div'))- fireEvent.click(outside)- outside.remove()- },- },- ])('unpins on $trigger', async ({ unpin }) => {- renderInsight({- query: buildTrendsQuery({- series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],- breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },- }),- })-- await chart.clickAtIndex(2)- expect(chart.getTooltip()).toBeInTheDocument()-- await unpin()-- await waitFor(() => {- expect(chart.getTooltip()).not.toBeInTheDocument()- })- })- })-describe('alert overlays', () => {it('does not render any alert overlay for an unsaved insight (insight.id is missing)', async () => {renderInsight({@@ -423,121 +325,52 @@ describe('TrendsLineChart', () => {expect(tooltip.row('Pageview')).toContain('134')expect(tooltip.element.textContent).not.toContain('Napped')})-- it('does not draw value labels or trend lines for a hidden series', async () => {- renderInsight({- query: buildTrendsQuery({- series: [- { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },- { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },- ],- trendsFilter: { showValuesOnSeries: true, showTrendLines: true },- }),- })-- await waitFor(() => {- // 2 main + 2 trend lines = 4 series- expect(screen.getByLabelText(/chart with 4 data series/i)).toBeInTheDocument()- })-- await legend.toggle('Napped')-- await waitFor(() => {- // Hiding Napped removes its main series + its trend line.- expect(screen.getByLabelText(/chart with 2 data series/i)).toBeInTheDocument()- })-- // No Napped value labels remain (Napped's data is 1, 3, 5, 8, 2; the 8 was the- // tallest distinct label so its absence is the cleanest signal).- const labels = getHogChart()- .valueLabels()- .map((l) => l.text)- expect(labels).not.toContain('8')- // Pageview labels should still be there.- expect(labels).toContain('210')- })})describe('axis labels', () => {- it.each([- {- name: 'renders custom axis titles from the trends filter',- trendsFilter: { xAxisLabel: 'Signup date', yAxisLabel: 'Unique users' },- expectedX: 'Signup date',- expectedY: 'Unique users',- },- {- name: 'renders no axis titles when the trends filter omits them',- trendsFilter: undefined,- expectedX: null,- expectedY: null,- },- ])('$name', async ({ trendsFilter, expectedX, expectedY }) => {+ it('renders custom axis titles from the trends filter', async () => {renderInsight({- query: buildTrendsQuery({ trendsFilter }),+ query: buildTrendsQuery({ trendsFilter: { xAxisLabel: 'Signup date', yAxisLabel: 'Unique users' } }),})await screen.findByLabelText(/chart with/i)- expect(getHogChart().xAxisLabel()).toBe(expectedX)- expect(getHogChart().yAxisLabel()).toBe(expectedY)+ expect(getHogChart().xAxisLabel()).toBe('Signup date')+ expect(getHogChart().yAxisLabel()).toBe('Unique users')})})describe('multi-axis', () => {- it.each([- { name: 'renders a right y-axis when showMultipleYAxes is true', enabled: true, expectedRight: true },- { name: 'omits the right y-axis by default', enabled: false, expectedRight: false },- ])('$name', async ({ enabled, expectedRight }) => {+ it('renders a right y-axis when showMultipleYAxes is true', async () => {renderInsight({query: buildTrendsQuery({series: [{ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },],- trendsFilter: enabled ? { showMultipleYAxes: true } : undefined,+ trendsFilter: { showMultipleYAxes: true },}),})await waitFor(() => {- expect(getHogChart().hasRightAxis).toBe(expectedRight)+ expect(getHogChart().hasRightAxis).toBe(true)})- if (expectedRight) {- expect(getHogChart().yRightTicks().length).toBeGreaterThan(0)- }+ expect(getHogChart().yRightTicks().length).toBeGreaterThan(0)})})describe('goal lines', () => {- // Pageview peaks at 210; a `displayIfCrossed: false` line below that peak is filtered out.- it.each([- {- name: 'single goal line renders with its label',- goalLines: [{ label: 'Target', value: 150, displayIfCrossed: true }],- expectedLabels: ['Target'],- },- {- name: 'multiple goal lines render in order',- goalLines: [- { label: 'Floor', value: 50, displayIfCrossed: true },- { label: 'Ceiling', value: 200, displayIfCrossed: true },- ],- expectedLabels: ['Floor', 'Ceiling'],- },- {- name: 'displayIfCrossed=false hides a line the data has crossed',- goalLines: [{ label: 'Crossed', value: 100, displayIfCrossed: false }],- expectedLabels: [],- },- ])('$name', async ({ goalLines, expectedLabels }) => {+ it('single goal line renders with its label', async () => {renderInsight({- query: buildTrendsQuery({ trendsFilter: { goalLines } }),+ query: buildTrendsQuery({+ trendsFilter: { goalLines: [{ label: 'Target', value: 150, displayIfCrossed: true }] },+ }),})await screen.findByLabelText(/chart with/i)await waitFor(() => {const lines = getHogChart().referenceLines()- expect(lines.map((l) => l.label)).toEqual(expectedLabels)+ expect(lines.map((l) => l.label)).toEqual(['Target'])for (const line of lines) {expect(line.orientation).toBe('horizontal')}@@ -590,13 +423,6 @@ describe('TrendsLineChart', () => {expect(l.text).toMatch(/%/)}})-- it('renders no labels when showValuesOnSeries is disabled', async () => {- renderInsight({ query: buildTrendsQuery() })-- await screen.findByLabelText(/chart with/i)- expect(getHogChart().valueLabels()).toHaveLength(0)- })})describe('log y-scale', () => {@@ -632,13 +458,6 @@ describe('TrendsLineChart', () => {expect(screen.getByLabelText(/chart with 2 data series/i)).toBeInTheDocument()})})-- it('omits the CI series from tooltip rows', async () => {- const tooltip = await chart.hoverTooltip(2)-- expect(tooltip.row('Pageview')).toContain('134')- expect(tooltip.element.textContent).not.toContain('(CI)')- })})describe('trend lines overlay', () => {@@ -650,12 +469,6 @@ describe('TrendsLineChart', () => {})})- it('adds a dashed trend-line series when enabled', async () => {- await waitFor(() => {- expect(screen.getByLabelText(/chart with 2 data series/i)).toBeInTheDocument()- })- })-it('omits the trend-line series from tooltip rows', async () => {const tooltip = await chart.hoverTooltip(2)@@ -740,11 +553,7 @@ describe('TrendsLineChart', () => {expect(personsModal.get()).not.toBeInTheDocument()})- it.each([- ['Spike', ['[email protected]']],- ['Bramble', ['[email protected]']],- ['Thistle', ['[email protected]']],- ] as const)('multi-series: clicking the %s row shows only %s actors', async (breakdown, expectedActors) => {+ it('multi-series: clicking the Spike row shows only Spike actors', async () => {renderInsight({query: buildTrendsQuery({series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],@@ -753,10 +562,10 @@ describe('TrendsLineChart', () => {})await chart.clickAtIndex(2)- await chart.clickTooltipRow(breakdown)+ await chart.clickTooltipRow('Spike')await waitFor(() => {- expect(personsModal.actorNames()).toEqual(expectedActors)+ expect(personsModal.actorNames()).toEqual(['[email protected]'])})})@@ -777,23 +586,6 @@ describe('TrendsLineChart', () => {expect(personsModal.get()).not.toBeInTheDocument()})- it('does nothing when there is no persons modal and no onDataPointClick', async () => {- renderInsight({- query: buildTrendsQuery({- trendsFilter: { formula: 'A + B' },- series: [- { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },- { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },- ],- }),- })-- await chart.clickAtIndex(2)-- // Without a click handler the canvas still renders; clicking is a no-op.- expect(personsModal.get()).not.toBeInTheDocument()- })-describe('shared mode', () => {beforeEach(() => {// Shared/exported pages set this global before React mounts; trendsDataLogic.hasPersonsModal reads it.@@ -879,28 +671,5 @@ describe('TrendsLineChart', () => {expect(legendEl.textContent).toContain('Napped')expect(legendEl.querySelector('button')).not.toBeInTheDocument()})-- it.each(['left', 'right'] as const)(- 'lays the legend out vertically when legendPosition is %s',- async (position) => {- const { container } = renderInsight({- query: buildTrendsQuery({- series: [- { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },- { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },- ],- trendsFilter: { showLegend: true, legendPosition: position },- }),- featureFlags: quillLegendFlag,- })-- await waitFor(() => {- expect(screen.getByLabelText(/chart with 2 data series/i)).toBeInTheDocument()- })-- const legendEl = getInChartLegend(container)- expect(legendEl.className).toContain('flex-col')- }- )})})diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.ts b/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.tsindex a6d28ebfa825..28626c856bc3 100644--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.ts@@ -74,17 +74,14 @@ describe('persons modal parity between ActionsPie and TrendsPieChart', () => {}}- it.each<[number, IndexedTrendResult]>([- [0, indexedResults[0]],- [1, indexedResults[1]],- ])('produces an identical query for slice %i', (sliceIndex, slice) => {+ it('produces an identical query for a slice', () => {const legacyQuery = datasetToActorsQuery({dataset: legacyActionsPieDataset(),query: querySource,- index: sliceIndex,+ index: 0,})const newQuery = datasetToActorsQuery({- dataset: newPieDatasetForSlice(slice),+ dataset: newPieDatasetForSlice(indexedResults[0]),query: querySource,})expect(newQuery).toEqual(legacyQuery)diff --git a/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.test.ts b/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.test.tsindex 9a9f46ee1f3a..049108babee6 100644--- a/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.test.ts+++ b/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.test.ts@@ -1,4 +1,3 @@-import { computeSeriesNonZeroMax } from '@posthog/quill-charts'import type { Series } from '@posthog/quill-charts'import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'@@ -18,26 +17,6 @@ const makeSeries = (data: number[], overrides: Partial<Series> = {}): Series =>})describe('goalLinesAdapter', () => {- describe('computeSeriesNonZeroMax', () => {- it('returns the max non-zero finite value across all series', () => {- const result = computeSeriesNonZeroMax([makeSeries([1, 2, 0, 5]), makeSeries([0, 0, 3, NaN])])- expect(result).toBe(5)- })-- it('ignores hidden series', () => {- const result = computeSeriesNonZeroMax([- makeSeries([1, 2, 3]),- makeSeries([1000], { key: 'b', visibility: { excluded: true } }),- ])- expect(result).toBe(3)- })-- it('returns 0 when no series have non-zero values', () => {- expect(computeSeriesNonZeroMax([makeSeries([0, 0, NaN])])).toBe(0)- expect(computeSeriesNonZeroMax([])).toBe(0)- })- })-describe('goalLinesToReferenceLines', () => {const series = [makeSeries([10, 20, 30])]@@ -73,15 +52,6 @@ describe('goalLinesAdapter', () => {expect(goalLinesToReferenceLines(goals, series)[0]).toMatchObject(expectedProps)})- it('drops goals when displayIfCrossed=false and value is below the series peak', () => {- const goals: SchemaGoalLine[] = [- { label: 'Crossed', value: 5, displayIfCrossed: false },- { label: 'Uncrossed', value: 100, displayIfCrossed: false },- ]- const result = goalLinesToReferenceLines(goals, series) // seriesMax = 30- expect(result.map((r) => r.label)).toEqual(['Uncrossed'])- })-it('keeps goals when displayIfCrossed is undefined or true', () => {const goals: SchemaGoalLine[] = [{ label: 'Default', value: 5 },diff --git a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsxnew file mode 100644index 000000000000..f63fc28c1706--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx@@ -0,0 +1,90 @@+import { renderHook } from '@testing-library/react'+import { BindLogic } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { DataNode, NodeKind, TrendsFilter, TrendsQuery } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { InsightLogicProps } from '~/types'++import { useInsightsLegendConfig } from './useInsightsLegendConfig'++const insightProps: InsightLogicProps = { dashboardItemId: undefined }++const wrapper = ({ children }: { children: React.ReactNode }): JSX.Element => (+ <BindLogic logic={insightLogic} props={insightProps}>+ {children}+ </BindLogic>+)++function setup({+ trendsFilter,+ flagEnabled = true,+}: { trendsFilter?: TrendsFilter; flagEnabled?: boolean } = {}): void {+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]: flagEnabled,+ })++ dataNodeLogic({ key: 'InsightViz.new', query: {} as DataNode }).mount()+ insightDataLogic(insightProps).mount()+ insightLogic(insightProps).mount()+ insightVizDataLogic(insightProps).mount()+ trendsDataLogic(insightProps).mount()+ const query: TrendsQuery = { kind: NodeKind.TrendsQuery, series: [], trendsFilter }+ insightVizDataLogic(insightProps).actions.updateQuerySource(query)+}++describe('useInsightsLegendConfig', () => {+ it('returns undefined when the quill legend flag is off', () => {+ setup({ flagEnabled: false, trendsFilter: { showLegend: true } })++ const { result } = renderHook(() => useInsightsLegendConfig({ insightProps }), { wrapper })++ expect(result.current).toBeUndefined()+ })++ it.each([+ { legendPosition: 'left', expected: 'left' },+ { legendPosition: 'right', expected: 'right' },+ { legendPosition: undefined, expected: 'right' },+ ] as const)('maps legendPosition $legendPosition to position $expected', ({ legendPosition, expected }) => {+ setup({ trendsFilter: { showLegend: true, legendPosition } })++ const { result } = renderHook(() => useInsightsLegendConfig({ insightProps }), { wrapper })++ expect(result.current?.position).toBe(expected)+ })++ it.each([+ { showLegend: true, expectedShow: true },+ { showLegend: undefined, expectedShow: false },+ ])('show is $expectedShow when trendsFilter.showLegend is $showLegend', ({ showLegend, expectedShow }) => {+ setup({ trendsFilter: { showLegend } })++ const { result } = renderHook(() => useInsightsLegendConfig({ insightProps }), { wrapper })++ expect(result.current?.show).toBe(expectedShow)+ })++ it.each([+ { inSharedMode: false, expectedInteractive: true },+ { inSharedMode: true, expectedInteractive: false },+ ])(+ 'interactive is $expectedInteractive when inSharedMode is $inSharedMode',+ ({ inSharedMode, expectedInteractive }) => {+ setup({ trendsFilter: { showLegend: true } })++ const { result } = renderHook(() => useInsightsLegendConfig({ insightProps, inSharedMode }), { wrapper })++ expect(result.current?.interactive).toBe(expectedInteractive)+ }+ )+})