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
@vitest/coverage-v8is the provider, the tool that counts the coverage. It reads the records V8 keeps about which code has run. V8 is the JavaScript engine in Node and Chrome. The other choice is@vitest/coverage-istanbul, which inserts counters into your code before it runs. The report looks the same.npx vitest --coverageruns every test and measures coverage at the same time. In a normal terminal, Vitest then waits for file changes (watch mode).npx vitest run --coverageruns just once, and that's what CI uses.
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
- % Stmts (statement coverage): the percentage of statements that ever ran. A statement is one instruction, such as
let fee = 20, anif, orreturn fee. The fileshipping.jshas 6 statements. - % Branch (branch coverage): the percentage of branches that were ever taken. Every
ifhas two branches: its condition is true (it enters the block) and false (it skips the block).else,switch, the ternarya ? b : c, and&&and||make branches too. This file has 2ifs, so 4 branches. - % Funcs (function coverage): the percentage of functions that were ever called. Here 1 out of 1.
- % Lines (line coverage): the percentage of lines holding code that ever ran. Close to Stmts, except one line can hold more than one statement.
- Uncovered Line #s: the lines that never ran. When every line has run, this column points at the lines whose branches are incomplete instead. Here
3-6doesn't mean lines 3 to 6. It means theifon line 3 and theifon line 6: both have a branch that was never taken.
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 |
- Test
(150, true): a member, so line 4 runs. The total is $150, so line 7 runs too. All six lines that hold a statement (lines 2, 3, 4, 6, 7 and 9) run: line coverage is 100%. - But the two false branches are never taken: "not a member" and "order under $100". Only 2 of the 4 branches, so branch coverage is 50%.
- Yet those false branches are the path most buyers take. No test proves an ordinary buyer pays $20.
- Add the test
(50, false), and all four branches are taken: 100% and 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,
},
},
},
});
reporter:textprints the table above in the terminal, andhtmlcreates acoverage/folder. Opencoverage/index.html: lines that never ran are red, and branches never taken are markedI(the if branch was never taken) orE(the else branch was never taken).include: the files that get counted. Without it, a file no test ever imports doesn't appear in the report at all, as if it were safe. Withinclude, that file appears at 0%.thresholds: the minimums. When coverage is below the minimum, Vitest printsERROR: Coverage for branches (50%) does not meet global threshold (80%)and exits with exit code 1 (a sign of failure). So the CI pipeline fails too.
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
- Being satisfied with 100% line coverage. Look at the % Branch column. 100% lines can mean only 50% branches.
- Tests without
expect. The lines run, coverage goes up, but nothing is checked. - Never trying the limit value. Tests at $150 and $50 never touch exactly $100, the one place where
>and>=differ. - Writing tests just for the number. Coverage is a map of what hasn't been tested yet, not a grade to chase.
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.