diff-cover-js
v0.3.1
Published
Diff coverage for JavaScript/TypeScript: line and branch coverage on changed lines only (patch coverage). Node.js alternative to Python diff-cover.
Maintainers
Readme
diff-cover-js
Diff coverage for JavaScript and TypeScript. Check test coverage, both line and branch coverage, only on the lines you changed in a pull request or git diff (patch coverage), not the entire file. Works with Jest, Vitest, Istanbul/nyc, c8 and any tool that writes lcov.info.
A Node.js alternative to the Python diff-cover: the same approach and similar flags, no Python required. See Differences from Python diff-cover.
Release notes: CHANGELOG.md.
Contents
- The problem it solves
- Installation · Requirements
- Usage: HTML + JSON reports, config file, library
- CLI flags · Default excluded patterns
- Jest setup · Vitest setup · GitHub Actions
- How it works · Uncommitted changes
- Output formats · Branch coverage
- Differences from Python diff-cover
- Development · License
The problem it solves
Standard coverage tools measure the whole file. If you add 10 lines to a 500-line file and cover all 10, Jest reports ~2% coverage. diff-cover-js reports 100% — because all your changed lines are covered.
Installation
Install it in your project as a dev dependency (recommended for CI, so every run uses the same version):
npm install --save-dev diff-cover-jsThen run it with npx diff-cover-js. To use it from any directory instead, install it globally:
npm install -g diff-cover-jsRequirements
- Node.js >= 16
- A
lcov.infofile generated by your test runner (Jest, Vitest, nyc and c8 all produce one with thelcovreporter) - A git repository with the base branch available locally
Usage
diff-cover-js \
--lcov coverage/lcov.info \
--compare-branch origin/main \
--fail-under 80By default this counts committed, staged and unstaged changes, like Python diff-cover. See Uncommitted changes.
Generate HTML + JSON reports
diff-cover-js \
--lcov coverage/lcov.info \
--compare-branch origin/main \
--fail-under 80 \
--format html:reports/diff-cover.html,json:reports/diff-cover.json,markdownUse a config file instead of flags
Create .diff-cover-js.json in your project root:
{
"lcov": "coverage/lcov.info",
"compareBranch": "origin/main",
"failUnder": 80,
"format": "html:reports/diff-cover.html,json",
"ignoreStaged": false,
"ignoreUnstaged": false,
"includeUntracked": false
}Then just run:
diff-cover-jsUse it as a library
import { getGitDiff, parseLcov, calculateDiffCoverage } from 'diff-cover-js';
const diffs = getGitDiff('origin/main', '...', {
ignoreStaged: false, // optional, same as --ignore-staged
ignoreUnstaged: false, // optional, same as --ignore-unstaged
includeUntracked: false, // optional, same as --include-untracked
});
const result = calculateDiffCoverage(diffs, parseLcov('coverage/lcov.info'));
console.log(result.overallPercent); // line coverage on changed lines
console.log(result.overallBranchPercent); // branch coverage on changed lines, null if noneIn --strict mode the source of a file missing from coverage is read from the working tree. Pass readSource to supply it yourself:
calculateDiffCoverage(diffs, lcov, { strict: true, readSource: (file) => myReadFile(file) });mergeLcovCoverage(into, from) is also exported for combining coverage records for the same file.
CLI flags
| Flag | Default | Description |
|------|---------|-------------|
| --lcov <path> | — | Path to lcov.info coverage file |
| --compare-branch <ref> | — | Git branch or ref to compare against (e.g. origin/main, FETCH_HEAD) |
| --fail-under <percent> | 0 | Exit code 1 if diff coverage is below this |
| --format <formats> | — | Output formats: html, json, markdown — with optional paths |
| --exclude <globs...> | — | Additional glob patterns to exclude on top of the built-in defaults |
| --no-default-excludes | off | Skip the built-in test/spec/.d.ts file exclusions entirely |
| --strict | off | Treat files missing from coverage data as 0% covered (only their code lines count; blank and comment lines are skipped, so a file where only comments changed shows ✓ 100%) |
| --diff-range-notation <...∣..> | ... | Git diff range notation (symmetric ... or simple ..) |
| --ignore-staged | off | Don't count staged changes |
| --ignore-unstaged | off | Don't count unstaged changes in the working tree |
| --include-untracked | off | Also count untracked files (not ignored by .gitignore); every line counts as added |
| -q, --quiet | off | Only print the final percentage, suppress the full report |
| -c, --config-file <path> | auto | Path to config file (auto-discovered if omitted) |
Default excluded patterns
These file patterns are excluded from diff coverage by default (test/spec files and type declarations). Use --no-default-excludes to opt out entirely, or just use --exclude to add more patterns on top.
**/*.test.ts **/*.test.tsx **/*.test.js **/*.test.jsx
**/*.spec.ts **/*.spec.tsx **/*.spec.js **/*.spec.jsx
**/__tests__/**
**/__mocks__/**
**/*.d.tsNote: The Python diff-cover tool has no built-in default exclusions — it relies on explicit
--excludeflags. The default exclusions here are a JS-ecosystem convenience. Pass--no-default-excludesto match the Python tool's behavior exactly.
Jest setup
Add lcov to your Jest coverage reporters:
// jest.config.js
module.exports = {
collectCoverage: true,
coverageDirectory: 'coverage',
coverageReporters: ['lcov', 'text'],
};Vitest setup
Install a coverage provider (npm i -D @vitest/coverage-v8) and add lcov to the reporters:
// vitest.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['lcov', 'text'],
},
},
});Then run npx vitest run --coverage. Istanbul/nyc (--reporter=lcov) and c8 (--reporter=lcov) also write a coverage/lcov.info that diff-cover-js reads.
Use in GitHub Actions
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history, needed to find the merge base
- run: npm ci
- run: npx jest --coverage --coverageReporters=lcov
- run: npx diff-cover-js --lcov coverage/lcov.info --compare-branch origin/main --fail-under 80The step fails (exit code 1) when coverage on changed lines is below 80%.
How it works
- Finds the base commit (
git merge-base <compare-branch> HEAD, or the compare branch itself with--diff-range-notation ..) and runsgit diff <base> --unified=0to get the exact lines you added, including staged and unstaged changes - Reads
lcov.infoto get per-line hit counts for instrumented files. If the same source file appears in severalSF:blocks (Jest multi-project setups, concatenated or sharded reports), or under different paths that resolve to the same file, the blocks are merged by adding hit counts, aslcovdoes - Cross-references: for each added line, is it in the coverage data and was it executed?
- Non-executable lines (blank lines, comments, type declarations) are automatically skipped — they don't count for or against coverage. With
--strict, a file with no lcov entry has no data to say which lines are executable, so its source is read from the working tree and blank and comment lines are skipped - Reports the percentage of your added executable lines that were covered
- If the lcov file has branch data (
BRDA:records), also counts the branches on your added lines that were taken at least once and reports them as a separate branch coverage figure
Uncommitted changes
Changed in 0.2.0: staged and unstaged changes are now counted by default, matching Python diff-cover. 0.1.x only counted committed changes (
git diff <compare-branch>...HEAD). In CI with a clean checkout the result is the same as before. If a CI step modifies tracked files before diff-cover-js runs (code generation,npm installrewritingpackage-lock.json, version stamping), those edits are now counted as changed lines; with--strict, files missing from coverage count as 0%. To get the 0.1.x behaviour, pass--ignore-staged --ignore-unstaged.
Line numbers in the report always refer to the file as it is on disk now, because that is what your tests ran against when they produced lcov.info. To keep them right, each mode uses a single diff against the base instead of combining separate committed/staged/unstaged diffs:
| Mode | Lines counted | How |
|------|---------------|-----|
| default | committed + staged + unstaged | git diff <base> (base vs working tree) |
| --ignore-unstaged | committed + staged | git diff --cached <base> (base vs index), line numbers mapped to the working tree through git diff |
| --ignore-staged --ignore-unstaged | committed only | git diff <base> HEAD, line numbers mapped to the working tree through git diff HEAD |
| --ignore-staged | committed + unstaged | git diff <base>, minus the lines whose current content came from a staged change (see below) |
| --include-untracked | adds untracked files | git ls-files --others --exclude-standard; every line of each text file counts as added. Binary files, symlinks and empty or unreadable files are skipped. Works with any of the modes above |
When a mode excludes some changes, a line is counted only if its current content comes from a change that is included. For example, with --ignore-unstaged, a staged line that you then edited again without staging is not counted, because what is on disk now is the unstaged edit. Lines that a later, excluded change moved are reported at their new position.
--ignore-staged on its own. No single git diff gives "committed + unstaged without staged". Python diff-cover runs the committed and unstaged diffs separately, then for each one removes that diff's deleted line numbers and adds its added ones. It doesn't shift the other line numbers, so they drift when both diffs touch the same file. diff-cover-js instead starts from git diff <base> (everything that differs from the base on disk). It then removes the lines added by the staged diff (git diff --cached HEAD), after moving them to their working-tree positions with git diff. Limitations:
- A line added in a commit and then modified by a staged change counts as staged, so it is excluded. Python counts it, at its line number in
HEAD. - A staged line that you edited again without staging counts as an unstaged change, so it is included.
- If your git config sets
diff.renames=false, a file renamed with a stagedgit mvis reported in full by--ignore-staged(your config treats it as a new file), but only its committed lines by--ignore-staged --ignore-unstaged. This errs towards counting more lines, so it can't hide an uncovered line.
Output formats
Console (default)
────────────────────────────────────────────────────────────────
diff-cover-js · Diff Coverage Report
✓ src/utils/foo.ts
100% diff coverage (5/5 coverable changed lines)
✗ src/services/bar.ts
60% diff coverage (3/5 coverable changed lines)
Missing lines: 42, 45
50% branch coverage (1/2 branches on changed lines)
Partially covered branches: 44
────────────────────────────────────────────────────────────────
Overall diff coverage: 80%
8/10 coverable changed lines covered
Overall branch coverage: 50%
1/2 branches on changed lines covered
────────────────────────────────────────────────────────────────HTML — table with per-file coverage % and missing line ranges
JSON — structured output for CI dashboards and PR comment bots
Markdown — for posting in PR descriptions
Branch coverage
If your lcov.info has branch data (BRDA: records, which Jest writes by default), the console and JSON reports also show branch coverage for the changed lines. It counts the branches on added lines that were taken at least once. The console report also lists the lines where a branch was never taken. The JSON report has the counts and percentages only.
- It is a separate figure. Line coverage and
--fail-underare not affected by it. - Branch data never changes line coverage. Python diff-cover, by contrast, uses lcov
BRDArecords to fill in lines that have noDArecord and to mark aDA0 line covered when one of its branches ran. Jest, Vitest and Istanbul write aDAline for every statement, so this rarely matters. If line coverage differs from Python diff-cover on the samelcov.info, this is the likely cause. - A branch that lcov reports as
-(not reached) counts as not taken. - Files or reports with no branches on the changed lines show no branch lines.
- The Markdown and HTML reports don't show branch data yet.
- The JSON report adds
coverableBranches,coveredBranchesandpercentBranchesCoveredper file, andtotalNumBranches,totalNumCoveredBranchesandtotalPercentBranchesCoveredat the top level. The percentages arenullwhen the changed lines have no branches.
Differences from Python diff-cover
| Feature | diff-cover (Python) | diff-cover-js |
|---------|---------------------|---------------|
| lcov support | ✓ | ✓ |
| HTML report | ✓ | ✓ |
| JSON report | ✓ | ✓ |
| Markdown report | ✓ | ✓ |
| Config file | TOML (pyproject.toml) | JSON (.diff-cover-js.json) |
| --ignore-staged / --ignore-unstaged / --include-untracked | ✓ | ✓ |
| Line numbers when committed, staged and unstaged changes touch the same file | Can drift: each diff's line numbers are combined without shifting | Always match the file on disk (see Uncommitted changes) |
| Code snippets in HTML | ✓ (via Pygments) | planned |
| diff-quality (lint violations) | ✓ | planned |
| Branch coverage on changed lines | No separate branch figure. For lcov, BRDA data only adjusts line coverage: it fills in lines with no DA record, and marks a DA 0 line covered if one of its branches ran. --branch-coverage (partial branches count as uncovered) applies only to Cobertura XML | Separate figure in the console and JSON reports; doesn't affect --fail-under |
| Cobertura XML input | ✓ | not planned (lcov only) |
| Runtime | Python | Node.js |
Development
npm install
npm run build # compile to dist/
npm test # vitest
npm run typecheck # type-check src/ and test/The package runs on Node.js >= 16, but the test tooling (vitest/vite) needs Node.js ^20.19 or >= 22.12.
License
MIT
