Test Coverage & Strategy — Testing

Test coverage measures what percentage of your code the tests run. The report gives four numbers: % Stmts (statements, or instructions), % Branch (branches…

The coverage report says 100%, so you're sure your shipping-fee function is fully tested. Yet not one test checks an ordinary buyer, one who isn't a member and spends little. And they're most of your buyers.

Test coverage measures what percentage of your code actually runs while your test suite (all of your tests together) runs. The number is useful, as long as you know what it doesn't measure. Picture a night guard who signs an attendance card in every room on his round. A card full of signatures proves he walked through every room, but not that he checked the windows were locked. In this picture, the guard is a test, the rooms are lines of code, and the attendance card is the coverage report. Checking the window locks is expect, and the card doesn't record it. So coverage records which lines the tests passed through, but not what was checked there.

The function we measure

A shop's shipping rule: shipping costs $20, members pay half, and orders from $100 ship free.

// src/shipping.js
export function calculateShipping(total, member) {
  let fee = 20;            // line 2
  if (member) {            // line 3
    fee = fee / 2;         // line 4: members pay half
  }
  if (total >= 100) {      // line 6
    fee = 0;               // line 7: free from $100
  }
  return fee;              // line 9
}

The line numbers in the comments follow the real file: line 1 is export function, because // src/shipping.js only names the file. For now, that function has only one test:

// src/shipping.test.js
import { test, expect } from "vitest";
import { calculateShipping } from "./shipping.js";

test("member, $150 order: free", () => {
  expect(calculateShipping(150, true)).toBe(0);
});

Running coverage

Install the coverage tool once, then run the tests with coverage:

npm install -D @vitest/coverage-v8
npx vitest --coverage

The result for that one test:

 Test Files  1 passed (1)
      Tests  1 passed (1)

 % Coverage report from v8
-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |       50 |     100 |     100 |                   
 shipping.js |     100 |       50 |     100 |     100 | 3-6               
-------------|---------|----------|---------|---------|-------------------

The four numbers in the report

Line coverage vs branch coverage

This table shows the coverage results for a few sets of tests. The first column holds the arguments of calculateShipping(total, member):

Tests that run % Lines % Branch Uncovered Line #s
(150, true) 100 50 3-6
(50, false) 66.66 50 4,7
(150, true) and (50, false) 100 100
(50, true) and (100, false) 100 100

That's why branch coverage is more honest than line coverage: lines can be at 100% while half the branches have never been taken.

100% coverage doesn't mean bug-free

Say line 6 is mistyped as if (total > 100). The two tests above stay green, and coverage stays at 100% on all four numbers. Yet an order of exactly $100 should ship free, and for an ordinary buyer this function returns 20. The bug only appears with a test right on the limit:

test("exactly $100: free", () => {
  expect(calculateShipping(100, false)).toBe(0);
});
 FAIL  src/shipping.test.js > exactly $100: free
AssertionError: expected 20 to be +0 // Object.is equality

Worse still, a test with no expect at all counts too. test("runs", () => { calculateShipping(150, true); }) gives 100% line coverage and checks nothing. Coverage only records the lines that ran. It doesn't record whether the results were checked. It also doesn't record whether edge cases (cases at the edge of a rule), such as limit values, zero or empty data, were tried. How to check that your tests really catch mistakes is the next lesson, Mutation Testing.

Thresholds and a sensible target

You set up coverage in Vitest's config file. Its thresholds part holds the thresholds, the minimum coverage you accept:

// vitest.config.js
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    coverage: {
      provider: "v8",
      reporter: ["text", "html"],
      include: ["src/**/*.js"],
      thresholds: {
        lines: 80,
        branches: 80,
        functions: 80,
        statements: 80,
      },
    },
  },
});

A common target: around 80% for important business code (prices, payments, validation), with extra attention on branches. Boilerplate (supporting code that is nearly the same in every project), config files and type definitions (files that only hold types) can be left out of the count. Chasing 100% usually ends in tests that just run code without checking anything.

⚠️ Coverage numbers that fool you

TL;DR: Test coverage measures what percentage of your code the tests run. The report gives four numbers: % Stmts (statements, or instructions), % Branch (branches, such as the true and false paths of an if/else, a ternary or &&), % Funcs (functions) and % Lines (lines). Run it with npx vitest --coverage (or npx vitest run --coverage in CI) after installing @vitest/coverage-v8, the tool that counts. 100% line coverage can mean only 50% branch coverage, so watch the branches. Even 100% doesn't guarantee bug-free code. A test can run every line without trying an edge case (a case at the edge of a rule, such as a limit value), even without an expect. Set thresholds (the minimums) so CI fails when coverage drops, aim for about 80% on important code, and use the report to find what hasn't been tested yet.

⚡ Running coverage

Write:

npm install -D @vitest/coverage-v8
npx vitest run --coverage

Meaning: Coverage is the percentage of your code that runs while the tests run, and @vitest/coverage-v8 is the tool that counts it. The report has four numbers: % Stmts (statements, or instructions), % Branch (branches, such as the true and false paths of an if), % Funcs (functions) and % Lines (lines). run runs once and exits, and that's what CI uses.

⚡ Lines 100%, branches 50%

Guess first: calculateShipping(total, member) has two ifs: members pay half the shipping, and orders from $100 ship free. There is only one test, calculateShipping(150, true). What are its line coverage and branch coverage?

Lines 100%, branches 50%. Every line runs, but the two false branches ("not a member" and "order under $100") are never taken.

Meaning: Branch coverage counts the if/else branches the tests took, so it's more honest than line coverage.

⚡ 100% doesn't mean bug-free

Write:

test("exactly $100: free", () => {
  expect(calculateShipping(100, false)).toBe(0);
});

Meaning: Coverage only records the lines that ran, not whether the results were checked or the limit was tried. If the >= in if (total >= 100) is mistyped as >, coverage can stay at 100%, and only this test right on the limit catches it.

What you will learn