Code Coverage

Measuring how much of your code is exercised by your tests

Overview

Code coverage measures how much of your source code runs while your tests execute, usually as a percentage of lines, branches, or functions. It highlights untested areas you may have forgotten. Coverage is a useful guide, not a goal in itself: 100% coverage does not prove the tests are meaningful, only that every line was reached.

Syntax / Usage

Most runners collect coverage with a single flag. Jest reports a table of covered lines, branches, and functions per file.

// discount.js
function applyDiscount(price, isMember) {
  if (isMember) {
    return price * 0.9;
  }
  return price;
}
module.exports = { applyDiscount };
# Run tests and print a coverage report
npx jest --coverage

To fail the build below a threshold, configure it in jest.config.js with coverageThreshold.

Examples

The test below only covers the member branch, so coverage will flag the other path:

const { applyDiscount } = require("./discount");

test("applies 10% discount for members", () => {
  expect(applyDiscount(100, true)).toBe(90);
});

Adding a test for the missing branch raises branch coverage to 100%:

test("charges full price for non-members", () => {
  expect(applyDiscount(100, false)).toBe(100);
});

Common Mistakes

  • Treating a high coverage number as proof the code is correct
  • Writing tests that run code but assert nothing, inflating coverage
  • Chasing 100% by testing trivial getters instead of real logic
  • Ignoring branch coverage and only watching line coverage
  • Excluding hard-to-test files just to make the number look better

See Also

testing-unit-tests testing-fundamentals testing-end-to-end