: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
fix(frontend): replace slow ByRole name queries in large-DOM jest tests (#68733)
Paul D'Ambra1f75c9ff1f18
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.mdindex 8e3120e091df..68f6fcc30017 100644--- a/.agents/skills/writing-tests/SKILL.md+++ b/.agents/skills/writing-tests/SKILL.md@@ -119,6 +119,10 @@ Escalating to the next rung is the last resort, not the default.- One top-level `describe` block per file (house rule).- Prefer logic tests over component renders (see the ladder above).- `test.each` for variations rather than copied test bodies.+- **Avoid `*ByRole(..., { name: ... })` on components that render a large DOM** (calendars, the taxonomic filter, whole scenes).+ Role queries walk every element running `getComputedStyle`-based checks and accessible-name computation — seconds per query in jsdom, multiplied by every `waitFor`/`findBy*` retry; this pattern has produced single tests with 40s p95 in CI.+ Prefer `getByText`, `getByTestId`/`data-attr` selectors, or `getByLabelText`; scope with `within(<small container>)` if a role query is genuinely needed.+ The `jest-no-byrole-name-queries` semgrep rule flags this.- **No huge snapshots.**A snapshot over a large rendered tree or serialized blob is a change-detector test that bloats the repo and breaks on every unrelated change.Snapshot a small, intentional value, or assert specific fields instead.diff --git a/.semgrep/rules/devex/jest-no-byrole-name-queries.yaml b/.semgrep/rules/devex/jest-no-byrole-name-queries.yamlnew file mode 100644index 000000000000..412eabc8d46d--- /dev/null+++ b/.semgrep/rules/devex/jest-no-byrole-name-queries.yaml@@ -0,0 +1,35 @@+rules:+ - id: jest-no-byrole-name-queries+ message: |+ `*ByRole(..., { name: ... })` in a jest/jsdom test. Role queries walk+ every element in the DOM, running `getComputedStyle`-based+ inaccessibility checks and computing accessible names as they go. In+ jsdom that costs tens of milliseconds per candidate element, so on a+ component that renders a large DOM (calendars with time columns, the+ taxonomic filter, whole scenes/dashboards) a single query takes+ seconds — and inside `waitFor`/`findBy*` the cost multiplies with+ every retry. This pattern has produced individual tests with p95+ durations of 40s in CI (see PostHog/posthog#68733).++ Prefer, in order:+ • `getByText(...)` when the assertion is about visible text+ • `getByTestId(...)` / a `data-attr` querySelector for interactions+ • `getByLabelText(...)` when the element is identified by aria-label+ • scope with `within(<small container>)` if a role query is genuinely needed++ This rule is informational, not blocking: role+name queries on small+ DOMs (a single button, a dialog) are fine, and are sometimes chosen+ deliberately for resilience to markup changes. If yours is one of+ those, add `// nosemgrep: jest-no-byrole-name-queries` with a short+ reason — but check the suite's runtime first.+ severity: WARNING+ languages: [typescript, javascript]+ paths:+ include:+ - '**/*.test.ts'+ - '**/*.test.tsx'+ pattern-regex: '(?:get|query|find)(?:All)?ByRole\(\s*[''"][a-z]+[''"]\s*,\s*\{[^}]*\bname\s*:'+ metadata:+ category: best-practice+ subcategory:+ - auditdiff --git a/frontend/src/lib/components/DateFilter/FixedRangeWithTimePicker.test.tsx b/frontend/src/lib/components/DateFilter/FixedRangeWithTimePicker.test.tsxindex d182e4eb0f7d..d88918d4655f 100644--- a/frontend/src/lib/components/DateFilter/FixedRangeWithTimePicker.test.tsx+++ b/frontend/src/lib/components/DateFilter/FixedRangeWithTimePicker.test.tsx@@ -148,7 +148,7 @@ describe('FixedRangeWithTimePicker', () => {await userEvent.click(minuteButton)// Start label should reflect the chosen time (regardless of fallback date).- expect(screen.getByRole('button', { name: /^Start: .* 14:30$/ })).toBeInTheDocument()+ expect(screen.getByText(/^Start: .* 14:30$/)).toBeInTheDocument()})describe('24-hour format', () => {@@ -163,8 +163,8 @@ describe('FixedRangeWithTimePicker', () => {/>)- expect(screen.getByRole('button', { name: 'Start: Jan 15, 2024 14:30' })).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'End: Jan 15, 2024 16:45' })).toBeInTheDocument()+ expect(screen.getByText('Start: Jan 15, 2024 14:30')).toBeInTheDocument()+ expect(screen.getByText('End: Jan 15, 2024 16:45')).toBeInTheDocument()})it('sets hours directly without AM/PM conversion', async () => {diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableCalendar.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableCalendar.test.tsxindex 07935af693d9..08660a9026cf 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableCalendar.test.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableCalendar.test.tsx@@ -28,8 +28,8 @@ describe('VariableCalendar', () => {</Provider>)- await userEvent.click(screen.getAllByRole('button', { name: '15' })[0])- await userEvent.click(screen.getByRole('button', { name: 'Apply' }))+ await userEvent.click(screen.getAllByText('15')[0])+ await userEvent.click(screen.getByText('Apply'))expect(updateVariable).toHaveBeenLastCalledWith('2026-03-15')@@ -42,8 +42,8 @@ describe('VariableCalendar', () => {</Provider>)- await userEvent.click(screen.getAllByRole('button', { name: '16' })[0])- await userEvent.click(screen.getByRole('button', { name: 'Apply' }))+ await userEvent.click(screen.getAllByText('16')[0])+ await userEvent.click(screen.getByText('Apply'))expect(updateVariable).toHaveBeenLastCalledWith('2026-03-16')})@@ -60,8 +60,8 @@ describe('VariableCalendar', () => {</Provider>)- await userEvent.click(screen.getAllByRole('button', { name: '15' })[0])- await userEvent.click(screen.getByRole('button', { name: 'Apply' }))+ await userEvent.click(screen.getAllByText('15')[0])+ await userEvent.click(screen.getByText('Apply'))expect(updateVariable).toHaveBeenLastCalledWith(expect.stringMatching(/^2026-03-15 \d{2}:\d{2}:00$/))@@ -78,11 +78,11 @@ describe('VariableCalendar', () => {</Provider>)- await userEvent.click(screen.getAllByRole('button', { name: '16' })[0])- await userEvent.click(screen.getByRole('button', { name: 'Apply' }))+ await userEvent.click(screen.getAllByText('16')[0])+ await userEvent.click(screen.getByText('Apply'))expect(updateVariable).toHaveBeenLastCalledWith(expect.stringMatching(/^2026-03-16 \d{2}:\d{2}:00$/))- }, 10000)+ })it('saves a date-only value when include time is off', async () => {const updateVariable = jest.fn()@@ -92,8 +92,8 @@ describe('VariableCalendar', () => {</Provider>)- await userEvent.click(screen.getByRole('button', { name: '15' }))- await userEvent.click(screen.getByRole('button', { name: 'Apply' }))+ await userEvent.click(screen.getByText('15'))+ await userEvent.click(screen.getByText('Apply'))expect(updateVariable).toHaveBeenCalledWith('2026-03-15')})diff --git a/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownFilter.test.tsx b/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownFilter.test.tsxindex 77c350596e25..da4f7070274a 100644--- a/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownFilter.test.tsx+++ b/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownFilter.test.tsx@@ -62,7 +62,8 @@ describe('TaxonomicBreakdownFilter', () => {const button = await waitForBreakdownButton()await userEvent.hover(button)await waitFor(() => {- const docsLink = screen.getByRole('link', { name: /read the docs/i })+ const docsLink = screen.getByText(/read the docs/i).closest('a')+ expect(docsLink).not.toBeNull()expect(docsLink).toHaveAttribute('href', 'https://posthog.com/docs/product-analytics/trends/breakdowns')})})@@ -109,7 +110,8 @@ describe('TaxonomicBreakdownFilter', () => {await userEvent.hover(button)await waitFor(() => {expect(screen.getByText(/single cohort breakdown/i)).toBeInTheDocument()- const docsLink = screen.getByRole('link', { name: /read the docs/i })+ const docsLink = screen.getByText(/read the docs/i).closest('a')+ expect(docsLink).not.toBeNull()expect(docsLink).toHaveAttribute('href','https://posthog.com/docs/product-analytics/trends/breakdowns#cohorts-and-breakdowns'diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFilterAddFilterPopover.test.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFilterAddFilterPopover.test.tsxindex f2dbfa066426..dc92ddebac3f 100644--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFilterAddFilterPopover.test.tsx+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFilterAddFilterPopover.test.tsx@@ -97,9 +97,9 @@ describe('RecordingsUniversalFilterAddFilterPopover (pill category dropdown)', (const personPropertiesItem = await screen.findByTestId('taxonomic-category-dropdown-item-person_properties')await userEvent.click(personPropertiesItem)- // The picked category is applied (findByRole waits for the re-render)...+ // The picked category is applied (findByLabelText waits for the re-render)...expect(- await screen.findByRole('button', { name: 'Current category: Person properties. Click to change.' })+ await screen.findByLabelText('Current category: Person properties. Click to change.')).toBeInTheDocument()// ...and the main filter stays open with its search query intact.diff --git a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowPropertyFiltersSearch.test.tsx b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowPropertyFiltersSearch.test.tsxindex e0f711cb5a56..a07d44546e49 100644--- a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowPropertyFiltersSearch.test.tsx+++ b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowPropertyFiltersSearch.test.tsx@@ -98,9 +98,9 @@ describe('HogFlowPropertyFilters search', () => {fireEvent.click(screen.getByTestId('taxonomic-tab-workflow_variables'))await waitFor(() => {- expect(screen.getAllByRole('button', { name: 'order_id' }).length).toBeGreaterThan(0)+ expect(screen.getAllByText('order_id').length).toBeGreaterThan(0)})- expect(screen.getAllByRole('button', { name: 'cart_total' }).length).toBeGreaterThan(0)+ expect(screen.getAllByText('cart_total').length).toBeGreaterThan(0)})it('filters workflow variables by search query in the dedicated tab', async () => {@@ -112,10 +112,10 @@ describe('HogFlowPropertyFilters search', () => {search('cart')await waitFor(() => {- expect(screen.getAllByRole('button', { name: 'cart_total' }).length).toBeGreaterThan(0)+ expect(screen.getAllByText('cart_total').length).toBeGreaterThan(0)})- expect(screen.queryByRole('button', { name: 'order_id' })).not.toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'shipping_country' })).not.toBeInTheDocument()+ expect(screen.queryByText('order_id')).not.toBeInTheDocument()+ expect(screen.queryByText('shipping_country')).not.toBeInTheDocument()})it('surfaces workflow variables in the All/Suggestions tab when searching', async () => {