Code coverage

suggest change

Code coverage tells you which parts of your code were executed while your tests ran. It doesn't prove the code is correct, but it is very good at showing what is definitely not tested: an error branch nobody triggers, a function nobody calls, a whole file nobody imports.

Node.js has two good options, both built on V8's native coverage (no code instrumentation, no Babel plugins):

Examples below were run with Node.js 24 and c8 12.

A project to measure

We'll use a small module with a few branches:

// src/price.js
export function applyDiscount(price, code) {
  if (price < 0) {
    throw new RangeError('price must be >= 0');
  }
  if (code === 'HALF') {
    return price / 2;
  }
  if (code === 'TENOFF') {
    return Math.max(0, price - 10);
  }
  return price;
}

export function formatPrice(cents, currency = 'USD') {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency })
    .format(cents / 100);
}

And an incomplete test file using node:test:

// test/price.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { applyDiscount } from '../src/price.js';

test('HALF halves the price', () => {
  assert.equal(applyDiscount(100, 'HALF'), 50);
});

test('unknown code leaves price unchanged', () => {
  assert.equal(applyDiscount(100, 'NOPE'), 100);
});

package.json:

{
  "name": "cov-demo",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "node --test",
    "coverage": "node --test --experimental-test-coverage"
  }
}

Coverage with the built-in test runner

Add --experimental-test-coverage to node --test:

$ npm run coverage
✔ HALF halves the price (0.7259ms)
✔ unknown code leaves price unchanged (0.091ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 92.6752
ℹ start of coverage report
ℹ ----------------------------------------------------------
ℹ file      | line % | branch % | funcs % | uncovered lines
ℹ ----------------------------------------------------------
ℹ src       |        |          |         |
ℹ  price.js |  58.82 |    66.67 |   50.00 | 3-4 9-10 15-17
ℹ ----------------------------------------------------------
ℹ all files |  58.82 |    66.67 |   50.00 |
ℹ ----------------------------------------------------------
ℹ end of coverage report

The report reads like this:

Test files themselves (*.test.js, files in test/ directories, etc.) and node_modules are excluded from the report automatically.

Despite the "experimental" in the flag name, this is stable enough for everyday use; the flag name is what may change.

Let's fill in the gaps:

// test/price.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { applyDiscount, formatPrice } from '../src/price.js';

test('HALF halves the price', () => {
  assert.equal(applyDiscount(100, 'HALF'), 50);
});

test('unknown code leaves price unchanged', () => {
  assert.equal(applyDiscount(100, 'NOPE'), 100);
});

test('TENOFF subtracts 10 but never goes below 0', () => {
  assert.equal(applyDiscount(25, 'TENOFF'), 15);
  assert.equal(applyDiscount(5, 'TENOFF'), 0);
});

test('negative price throws', () => {
  assert.throws(() => applyDiscount(-1), RangeError);
});

test('formatPrice formats cents', () => {
  assert.equal(formatPrice(123456), '$1,234.56');
});
ℹ start of coverage report
ℹ ----------------------------------------------------------
ℹ file      | line % | branch % | funcs % | uncovered lines
ℹ ----------------------------------------------------------
ℹ src       |        |          |         |
ℹ  price.js | 100.00 |   100.00 |  100.00 |
ℹ ----------------------------------------------------------
ℹ all files | 100.00 |   100.00 |  100.00 |
ℹ ----------------------------------------------------------
ℹ end of coverage report

Line coverage vs. branch coverage

100% line coverage doesn't mean every path was taken. Look at this one-liner:

// src/shipping.js
export function shippingCost(total) {
  return total >= 50 ? 0 : 4.99;
}
// test/shipping.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { shippingCost } from '../src/shipping.js';

test('free shipping over $50', () => {
  assert.equal(shippingCost(80), 0);
});
$ node --test --experimental-test-coverage test/shipping.test.js
...
ℹ file         | line % | branch % | funcs % | uncovered lines
ℹ -------------------------------------------------------------
ℹ src          |        |          |         |
ℹ  shipping.js | 100.00 |    66.67 |  100.00 |

Every line ran, but the 4.99 side of the ternary never did. Branch coverage catches it. If you track only one number, track branches.

Failing the run below a threshold

Thresholds turn coverage into a check. When coverage is below the minimum, the test run exits with code 1, which fails npm test and any CI job:

$ node --test --experimental-test-coverage \
    --test-coverage-lines=80 \
    --test-coverage-branches=70 \
    --test-coverage-functions=50
...
ℹ Error: 58.82% line coverage does not meet threshold of 80%.
ℹ Error: 66.67% branch coverage does not meet threshold of 70%.
...
$ echo $?
1

(This is against the incomplete version of the tests.) The thresholds are percentages of the totals for all files, not per file.

A practical approach: set thresholds slightly below your current numbers so coverage can't silently drop, and ratchet them up over time. Chasing 100% everywhere usually produces tests that execute code without asserting anything meaningful.

Choosing which files are reported

By default every file loaded during the tests is reported, except test files and node_modules. Narrow it down with glob patterns; both flags can be repeated:

# only report on application code, skip generated files
node --test --experimental-test-coverage \
  --test-coverage-include='src/**' \
  --test-coverage-exclude='src/generated/**'

Quote the globs so the shell doesn't expand them.

Important limitation: the built-in runner only knows about files that were actually loaded. A module that no test imports doesn't show up at all, not even as 0%, so it doesn't lower your totals. --test-coverage-include doesn't change that. If you want untested files to count against you, use c8 with --all (shown below).

Ignoring code

Some code is impractical to test: platform-specific branches, defensive checks for "impossible" states, debug helpers. You can exclude it with special comments:

// src/port.js
export function parsePort(value) {
  const n = Number(value);
  /* node:coverage ignore next 3 */
  if (!Number.isInteger(n) || n < 1 || n > 65535) {
    throw new RangeError(`invalid port: ${value}`);
  }
  return n;
}

/* node:coverage disable */
export function debugDump(obj) {
  console.error(JSON.stringify(obj, null, 2));
}
/* node:coverage enable */

With a test that only calls parsePort('8080'), the file reports 100% / 100% / 100%. Without the comments it would be 71.43% lines, 66.67% branches, 50% functions.

Use this sparingly. Every ignore comment is a small lie in the report; if you write one, it should be obvious to a reviewer why the code can't reasonably be tested.

c8 understands the same node:coverage comments, as well as its own /* c8 ignore next */, /* c8 ignore next 3 */ and /* c8 ignore start */ ... /* c8 ignore stop */.

LCOV output for editors and services

The summary table is for humans. Tools (Codecov, Coveralls, SonarQube, the VS Code "Coverage Gutters" extension) want LCOV. The built-in runner has an lcov reporter. Combine it with a regular reporter so you still see test results:

node --test --experimental-test-coverage \
  --test-reporter=spec --test-reporter-destination=stdout \
  --test-reporter=lcov --test-reporter-destination=lcov.info

Each --test-reporter is paired with the --test-reporter-destination that follows it. The resulting lcov.info is a plain text file with per-line hit counts:

TN:
SF:src/price.js
FN:1,applyDiscount
FN:14,formatPrice
FNDA:2,applyDiscount
FNDA:0,formatPrice
FNF:2
FNH:1
...
DA:1,1
DA:2,2
DA:3,0
DA:4,0
...
LH:10
LF:17
end_of_record

DA:3,0 means line 3 executed 0 times, FNDA:0,formatPrice means formatPrice was never called.

Coverage from code: the run() API

The test runner's run() function accepts the same options, which is handy for custom test scripts:

// run-coverage.mjs
import { run } from 'node:test';
import { spec } from 'node:test/reporters';

run({
  files: ['test/price.test.js'],
  coverage: true,
  coverageIncludeGlobs: ['src/**'],
  lineCoverage: 100,
})
  .on('test:coverage', ({ summary }) => {
    console.log('lines:', summary.totals.coveredLinePercent.toFixed(2) + '%');
  })
  .compose(spec)
  .pipe(process.stdout);

The test:coverage event gives you the full data: summary.files has per-file line, branch and function details, and summary.totals has the overall numbers (coveredLinePercent, coveredBranchPercent, coveredFunctionPercent, plus raw counts).

c8: HTML reports, --all, and any test framework

c8 runs a command with V8 coverage enabled, collects the data from all processes it spawns (including child processes and workers), and turns it into Istanbul reports. It works with node --test, Mocha, a plain script, anything that runs on Node.

npm install --save-dev c8

Prefix your test command with c8:

$ npx c8 node --test
...
-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |    91.66 |     100 |     100 |
 price.js    |     100 |      100 |     100 |     100 |
 shipping.js |     100 |    66.66 |     100 |     100 | 2
-------------|---------|----------|---------|---------|-------------------

With Mocha it's the same idea: c8 mocha.

Including untested files

Add a src/slugify.js that no test imports. Without --all it's invisible, same as with the built-in runner. With --all and --src, c8 also scans the source directory and reports unloaded files as 0%:

$ npx c8 --all --src src --reporter=text --reporter=html node --test
...
-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files    |   86.95 |    84.61 |      75 |   86.95 |
 price.js    |     100 |      100 |     100 |     100 |
 shipping.js |     100 |    66.66 |     100 |     100 | 2
 slugify.js  |       0 |        0 |       0 |       0 | 1-3
-------------|---------|----------|---------|---------|-------------------

This is the honest number: a file with no tests at all is the biggest coverage gap you can have.

HTML report

--reporter=html writes coverage/index.html. Open it in a browser to get a sortable list of files and each file's source with uncovered lines highlighted in red and untaken branches marked inline. This is by far the fastest way to see what you're missing. Add coverage/ to .gitignore.

Useful reporters: text (the table), text-summary (four totals), html, lcov (writes both coverage/lcov.info and an HTML report), json-summary, cobertura (for GitLab and Azure DevOps).

Configuration file

Instead of a long command line, put the options in .c8rc.json at the project root:

{
  "all": true,
  "src": ["src"],
  "exclude": ["test/**", "coverage/**"],
  "reporter": ["text", "html", "lcov"],
  "check-coverage": true,
  "lines": 90,
  "branches": 85,
  "functions": 90
}

Now npx c8 node --test uses them. With check-coverage enabled, c8 exits with code 1 when a threshold isn't met:

ERROR: Coverage for lines (86.95%) does not meet global threshold (90%)
ERROR: Coverage for functions (75%) does not meet global threshold (90%)
ERROR: Coverage for branches (84.61%) does not meet global threshold (85%)

Add "per-file": true to apply the thresholds to each file instead of to the totals.

You can regenerate reports from the last run's data without re-running tests:

$ npx c8 report --reporter=text-summary

=============================== Coverage summary ===============================
Statements   : 86.95% ( 20/23 )
Branches     : 84.61% ( 11/13 )
Functions    : 75% ( 3/4 )
Lines        : 86.95% ( 20/23 )
================================================================================

How it works: NODE_V8_COVERAGE

Both tools rely on the same Node.js feature. When the NODE_V8_COVERAGE environment variable points to a directory, Node enables V8's precise coverage and, when the process exits, writes the raw data as JSON there:

$ NODE_V8_COVERAGE=cov node -e "Math.max(1, 2)"
$ ls cov
coverage-34900-1792255124553-0.json

Child processes inherit the environment variable, so they write their own files. That's how c8 covers code in spawned processes. The raw files list byte ranges and execution counts per function and block; c8 (via v8-to-istanbul) maps them back to lines and branches, using source maps when present, so TypeScript compiled with source maps reports against the .ts files.

Because the counting is done by the V8 engine itself, there's no instrumentation step and the overhead is small, unlike older tools such as nyc/Istanbul which rewrote your code before running it. For new projects there's little reason to use nyc.

Which one to use

node --test --experimental-test-coverage c8
Install nothing dev dependency
Test framework node:test only any
Unloaded files not reported reported with --all
Output text table, LCOV text, HTML, LCOV, Cobertura, JSON ...
Thresholds --test-coverage-lines etc. --check-coverage --lines etc., optional per file
Ignore comments node:coverage node:coverage and c8 ignore

If you already use node:test, start with the built-in coverage and add c8 when you want an HTML report or --all. If you use Mocha or another runner, use c8.

To run coverage on every push and upload the report as a build artifact, see Testing in CI. For writing the tests themselves, see Mocks and test doubles.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents