How to Run Only Affected Tests in CI
Most PRs touch a fraction of the codebase but rerun the whole suite. Running only affected tests scales CI to the size of the diff.
Affected-test selection maps a code change to the tests that exercise it and runs only those on PRs. The full suite still runs on the main branch as a safety net.
1. Scope by changed files
Compute the diff against the base branch and pass the changed paths to your test runner.
- run: |
CHANGED=$(git diff --name-only origin/main...HEAD)
npx jest --findRelatedTests $CHANGED --ci2. Use monorepo affected detection
Nx and Turborepo compute an affected graph from the diff and run tasks only for impacted projects.
- run: npx nx affected -t test --base=origin/main3. Map tests to code with coverage
Tools like pytest-testmon and Jest related-tests track which tests cover which lines, so the selection is based on real coverage, not file-name guessing.
4. Always run the full suite on main
Affected selection is for fast PR feedback. Keep an unconditional full run on the default branch so nothing slips through a missed dependency edge.
Key takeaways
- Map the diff to the tests that exercise it and run only those on PRs.
- Monorepo tools give an affected graph for free.
- Keep a full suite run on main so missed edges are still caught.