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(ci): select jest tests from runtime imports (#116327)

Raúl Negrón-Oterof62f19f4224c
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.yml
index 4260a6e21cb5..6004f36cbc84 100644
--- a/.github/workflows/ci-frontend.yml
+++ b/.github/workflows/ci-frontend.yml
@@ -369,19 +369,20 @@ jobs:
fi
# Skip selection when jest config / build / lock files change, or
- # when replay-shared source changes: that package sits outside
- # the frontend jest roots, so --findRelatedTests misses its
- # frontend consumers. Pattern matches mirror the frontend_code
+ # when a file changes whose consumers --findRelatedTests misses.
+ # replay-shared sits outside the frontend jest roots. Jest loads
+ # the MSW mocks for every test through a setup file, so no test
+ # has to import them. Pattern matches mirror the frontend_code
# paths-filter in `changes`.
while IFS= read -r f; do
case "$f" in
- jest.*.ts|babel.config.js|tsconfig.json|tsconfig.*.json|\
+ frontend/jest.*|babel.config.js|tsconfig.json|tsconfig.*.json|\
package.json|pnpm-lock.yaml|webpack.config.js|\
.github/workflows/ci-frontend.yml|.github/scripts/jest-retries.cjs|patches/[email protected]|.nvmrc)
fall_back config_change "$f"
exit 0
;;
- common/replay-shared/src/*)
+ common/replay-shared/src/*|frontend/src/mocks/*|frontend/src/lib/api.mock.ts)
fall_back unindexed_dependency "$f"
exit 0
;;
diff --git a/docs/internal/ci-things-already-tried.md b/docs/internal/ci-things-already-tried.md
index 39866878ba6c..020bce2ec413 100644
--- a/docs/internal/ci-things-already-tried.md
+++ b/docs/internal/ci-things-already-tried.md
@@ -214,6 +214,10 @@ Read the comment at the top of `.github/workflows/ci-backend.yml` for the curren
The jest and Playwright suites made the same move later, so `ready_for_review` no longer buys a full matrix anywhere.
Selection now runs on drafts and ready PRs alike in `ci-backend.yml`, `ci-frontend.yml`, `ci-storybook.yml`, and `ci-e2e-playwright.yml`, and the merge queue's `trunk-merge/**` run is the only full gate.
Jest selection includes imported JSON files, such as terminal package manifests, because changes to data can break their consumers without changing TypeScript.
+Frontend jest selection follows only the imports that load a module when a test runs.
+An import used only as a type does not select a test, because the jest transformer removes it.
+Jest loads its configuration, its setup files, and the MSW mocks for every test, so selection cannot follow a change to one of them through imports.
+A ready PR that changes one takes the full matrix.
What still differs by draft state is the fallback when a selection cannot be trusted: a draft skips the suite and defers to its ready run, a ready PR takes the full matrix because no later run on that PR would cover it.
_Also asked as:_ snob, is test selection on, why does CI run all the tests, do we select tests on PRs
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index 1961190e67ac..6cc30fcbf8e3 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -177,6 +177,9 @@ const config: Config = {
// (whose Node subpaths are null under `browser`) without affecting any other package's resolution.
resolver: '<rootDir>/jest.resolver.js',
+ // Runs `@sucrase/jest-plugin` on each file, so a change to the `transform` entry below must change it too.
+ dependencyExtractor: '<rootDir>/jest.dependencyExtractor.js',
+
modulePaths: ['<rootDir>/'],
roots: rootDirectories(),
diff --git a/frontend/jest.dependencyExtractor.js b/frontend/jest.dependencyExtractor.js
new file mode 100644
index 000000000000..d804d3e04372
--- /dev/null
+++ b/frontend/jest.dependencyExtractor.js
@@ -0,0 +1,22 @@
+const crypto = require('crypto')
+const fs = require('fs')
+
+const sucraseJest = require('@sucrase/jest-plugin')
+const { getVersion } = require('sucrase')
+
+// Jest reads imports from source text, where an import used only as a type looks like one that
+// loads a module. Reading them from the transformed code keeps the imports that exist at run time.
+module.exports = {
+ extract(code, filePath, defaultExtract) {
+ let source = code
+ try {
+ source = sucraseJest.process(code, filePath, {}).code
+ } catch {
+ // A file the transformer cannot parse keeps every import its source names.
+ }
+ return defaultExtract(source, filePath)
+ },
+ getCacheKey() {
+ return crypto.createHash('sha1').update(fs.readFileSync(__filename)).update(getVersion()).digest('hex')
+ },
+}
diff --git a/frontend/src/test/jest.dependencyExtractor.test.ts b/frontend/src/test/jest.dependencyExtractor.test.ts
new file mode 100644
index 000000000000..03a2f455777d
--- /dev/null
+++ b/frontend/src/test/jest.dependencyExtractor.test.ts
@@ -0,0 +1,35 @@
+import dependencyExtractor from '../../jest.dependencyExtractor'
+
+const namedModules = (code: string): Set<string> =>
+ new Set([...code.matchAll(/(?:require\(|from\s+)['"]([^'"]+)['"]/g)].map((match) => match[1]))
+
+describe('jest.dependencyExtractor', () => {
+ it.each([
+ [
+ 'drops an import used only as a type',
+ 'shape.ts',
+ `import { Shape } from './shape'\nexport const area = (shape: Shape): number => shape.width`,
+ [],
+ ],
+ [
+ 'keeps an import used as a value',
+ 'run.ts',
+ `import { helper } from './helper'\nexport const run = (): void => helper()`,
+ ['./helper'],
+ ],
+ [
+ 'keeps an import used only in JSX',
+ 'Page.tsx',
+ `import { Button } from './Button'\nexport const Page = (): JSX.Element => <Button />`,
+ ['./Button'],
+ ],
+ [
+ 'keeps every import of a file the transformer cannot parse',
+ 'broken.ts',
+ `import { Shape } from './shape'\nconst = `,
+ ['./shape'],
+ ],
+ ])('%s', (_name, filePath, code, expected) => {
+ expect([...dependencyExtractor.extract(code, filePath, namedModules)]).toEqual(expected)
+ })
+})