Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 30 ยท Jest in Real Projects

Coverage and Test Quality

Measure code coverage with Jest: read the report, set coverageThreshold, understand line vs branch coverage and why coverage is not quality, with a coverage counter stand-in.

Once you have a few dozen tests, a natural question appears: which parts of my code do these tests never run? Code coverage answers it. Jest can instrument your source files, record which statements, branches and functions executed during the test run, and print a report.

Coverage is a useful flashlight and a poor judge. It shows you code that has no tests at all, but it cannot tell you whether the tests that do run check anything. This lesson shows how to collect and read coverage, how to enforce a minimum in CI, and why a high number can still hide weak tests.

Real versus stand-in. The commands and config are real Jest usage, shown read-only. The TryIt blocks use hand-written stand-ins: one counts which statements and branches ran, and one performs a tiny mutation test. Real Jest instruments code automatically through Babel or V8, which is far more complete.

What coverage measures

Statements Did each statement run?
Branches Did both sides of each if run?
Functions Was each function called?
Lines Did each source line run?

Running code is not the same as checking it.

1 / 2

Collecting coverage

Add the flag to any run:

Terminal
npx jest --coverage

Or switch it on in the config, and choose what to measure:

JavaScript
module.exports = {
  collectCoverage: true,
  collectCoverageFrom: ["src/**/*.js", "!src/**/*.test.js"],
  coverageDirectory: "coverage",
  coverageReporters: ["text", "lcov"],
};

collectCoverageFrom is worth setting. Without it, Jest only reports files that at least one test imported, so a source file with no tests at all simply does not appear, and your numbers look better than the truth.

The report goes to the terminal as a table (text) and, with lcov, to coverage/lcov-report/index.html. Open that page in a browser to see every source line coloured by whether it ran. It is the most useful view, because you can click straight to the untested lines.

A text report looks like this (the numbers are an example):

TEXT
-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |   88.89 |       75 |     100 |   88.89 |
 price.js  |   88.89 |       75 |     100 |   88.89 | 9
-----------|---------|----------|---------|---------|-------------------

The last column names the lines that never ran. That is your to-do list.

Line coverage versus branch coverage

Consider this function:

JavaScript
function shipping(total, isMember) {
  if (total > 50 || isMember) {
    return 0;
  }
  return 5;
}

A single test, shipping(100, false), runs the if and the return 0 line. Line coverage for those two lines is satisfied, yet the return 5 path is untested. Branch coverage counts each outcome of each decision separately, so it notices the missing "false" side. It is stricter and usually more honest than line coverage.

Even branch coverage is not complete. Istanbul, the engine behind Jest's default coverage, also treats the operands of || and && as branches, but no report can promise that every combination of inputs was tried.

Thresholds

You can make Jest fail when coverage drops below a number. That turns coverage into a safety net in CI:

JavaScript
module.exports = {
  collectCoverage: true,
  coverageThreshold: {
    global: { branches: 80, functions: 80, lines: 80, statements: 80 },
    "./src/payments/": { branches: 95 },
  },
};

If a threshold is not met, Jest prints which one failed and exits with a non-zero code, so a CI job fails. Per-folder thresholds let you demand more of critical code like payments than of the rest.

Do not chase 100 percent. The last few percent often cover trivial or defensive code, and forcing it leads to tests that exist only to satisfy the tool. A steady 80 to 90 percent with strong assertions beats 100 percent with weak ones. Use thresholds to stop coverage from falling, not to set a trophy.

You can also exclude code that is not worth measuring with coveragePathIgnorePatterns (for example generated files), or mark a single block with a comment such as /* istanbul ignore next */. Use that sparingly and explain why.

Stand-in 1: a coverage counter

How does a tool know a line ran? It adds a counter in front of it. The stand-in below does that by hand: the function calls hit("name") at each statement and each branch, and a small report turns the counters into percentages. Real Jest inserts such counters automatically; this is only the idea.

Node.js A hand-made coverage counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

After the first call, one of the two branches never ran, which is the lesson: a single "happy path" test leaves a hole that the report points straight at. A second test closes it.

Coverage is not quality

Here is a test that gives full coverage and proves nothing:

JavaScript
test("shipping runs", () => {
  shipping(100, false);
  shipping(10, false);
});

Every line and branch executes, so the report says 100 percent. But there is no expect, so the test would pass even if shipping returned the wrong amounts. Coverage measures what ran, not what was verified.

A direct way to check test strength is mutation testing. A tool makes small changes to your code (turning > into >=, + into -, true into false), then runs your tests against each change. If the tests still pass, the mutant "survived", which means no test depended on that detail. In the JavaScript world, Stryker is the best-known tool for this. It is slow, because it runs the suite many times, so teams usually run it on the most important modules or on a schedule.

Stand-in 2: a tiny mutation test

The sketch below mutates one operator by hand and runs two test suites against each version of the code. The weak suite lets a mutant survive; the strong one catches it. This is a model of the idea, not Stryker.

Node.js Killing and surviving mutants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The weak suite never tries the boundary value 50, so changing > to >= goes unnoticed. The strong suite includes it, and fails on the mutant, which is exactly what you want. Boundary values are where coverage numbers look fine and bugs still hide. Table-Driven Tests with test.each is a tidy way to list them.

Habits that keep coverage honest

  • Set collectCoverageFrom so untested files show up as 0 percent.
  • Read the HTML report and look at uncovered branches, not only the total.
  • Fail CI on a threshold, but review it as a team rather than raising it blindly.
  • Prefer a failing assertion over a covered line: ask "what would break this test?" for each important test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why set collectCoverageFrom?

    Without it Jest only reports files that were loaded during the run, so completely untested files hide from the numbers.
  2. 2. A test calls shipping(100, false) only. Which kind of coverage is most likely to reveal the gap?

    The function was called and its lines mostly ran, but the else path never did. Branch coverage counts each outcome separately and reports it.
  3. 3. A test file has no expect calls but runs every line of a module. What does the coverage report say?

    Coverage measures execution, not verification. This is why assertions and mutation testing matter.
  4. 4. What does a surviving mutant tell you?

    If the tests still pass after the code is changed, then nothing checked that detail, so the tests are weaker than they look.

Summary

  • jest --coverage reports statements, branches, functions and lines; the HTML report shows exactly which lines never ran.
  • Use collectCoverageFrom so untested files are counted, and coverageThreshold to fail CI when numbers fall.
  • Branch coverage is stricter than line coverage because it counts both outcomes of every decision.
  • Coverage shows what was executed, not what was verified; mutation testing probes whether tests really notice changes.
  • Aim for steady, meaningful coverage rather than a perfect number.

Next, apply Jest to a browser-style interface in Testing UI with jsdom and Testing Library.