Jest · Unit tests that survive refactors
How should Jest run in CI?
Short answer
Run with --ci on a clean install, keep the run deterministic, publish a machine-readable report, and fail on uncommitted snapshots. Cache the transform output rather than test results.
CI is a different environment from a laptop: fewer cores, no interactive terminal and no developer watching the output. The suite needs to be deterministic, produce artifacts that survive the job, and fail for real reasons rather than environment differences.
npx jest --ci --coverage --maxWorkers=2 --reporters=default --reporters=jest-junitCI practices that help
- Use a lockfile install so the runner matches local dependency versions
- Set a worker count that matches the runner's memory, not its core count alone
- Publish coverage and test reports as build artifacts
- Run
jest --ciso new snapshots fail instead of being written silently - Shard large suites across jobs by test path pattern
- Clear the transform cache only when the cache key changes
A flaky test is worse in CI because it blocks unrelated work. Track flaky tests explicitly, fix the isolation or async wait, and do not normalize retries as a permanent solution. Retrying hides the bug and adds latency.
--ci mode Jest will not create a missing snapshot, which catches a test that only passed locally because an uncommitted snapshot existed.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What does the --ci flag change about snapshots?
- 2How do you shard a Jest suite across CI jobs?
- 3Why is retrying a flaky test a poor long-term fix?
- 4How many workers should CI use?
Say it in the interview
I run Jest with the ci flag on a lockfile install, with a worker count matched to the runner's memory. I publish coverage and a JUnit report so failures are visible in the pull request. Snapshots must be committed, because ci mode will not write new ones. Flaky tests I fix rather than retry, since retries hide real isolation or async bugs.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.