Jest · Unit tests that survive refactors
How does code coverage work in Jest?
Short answer
Run Jest with --coverage to instrument code and report statements, branches, functions and lines. Coverage shows what executed, not whether the assertions were meaningful.
Coverage is collected through Istanbul instrumentation. Jest records which statements, branches, functions and lines executed while the tests ran, then reports the percentage per file. It is a map of untested code, not a measure of test quality.
npx jest --coverage
npx jest --coverage --collectCoverageFrom="src/**/*.{ts,tsx}"The four metrics
- Statements: how many executable statements ran
- Branches: how many paths through if, switch, ternary and logical expressions ran
- Functions: how many functions were called
- Lines: how many source lines executed
High coverage with weak assertions is common. A test that renders a component and asserts nothing can cover every line. Branch coverage is often the more useful signal because it exposes untested conditions, but even full branch coverage does not prove the right outcomes were checked.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Which coverage metric is most useful and why?
- 2Why can a test have high coverage and still be useless?
- 3How do you exclude files from the coverage report?
- 4Does 100 percent coverage mean the code is correct?
Say it in the interview
Jest instruments the source and reports statements, branches, functions and lines. I use it to find untested areas, especially untested branches. Coverage does not measure assertion quality, so a render-only test can hit every line and prove nothing. I exclude generated and type-only files so the number reflects code that actually needs tests.
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.