Jest Code Coverage Thresholds: Enforcing Quality Gates
Jest's coverageThreshold configuration lets you define minimum code coverage percentages—globally or per-file—and fail the test run when they drop below the threshold. This turns coverage into a quality gate: no PR can merge if it introduces untested code that pushes coverage below your floor. Combined with --coverage in CI, you get automatic enforcement without relying on developers remembering to check coverage reports.
Key Takeaways
Coverage thresholds enforce floors, not ceilings. You set minimums. The goal isn't 100% coverage—it's ensuring coverage doesn't drop. Even 70% enforced is better than 90% that nobody checks.
Four metrics: lines, statements, branches, functions. Branches (if/else, ternaries, switch cases) are the hardest to cover and the most valuable. Set a branch threshold to force coverage of conditional logic.
Per-file thresholds catch regressions in specific modules. Global thresholds can mask a single file dropping to 10% coverage if everything else is at 90%. Per-file thresholds prevent this.
Use --coverage in CI, not locally by default. Coverage instrumentation slows tests. Run coverage in CI pipelines; run fast tests locally.
Start low and ratchet up. Set thresholds slightly below your current coverage, then raise them over time. Starting at 100% on a legacy codebase causes immediate CI failures and developer frustration.
Basic Coverage Threshold Configuration
// jest.config.js
module.exports = {
collectCoverage: true,
coverageDirectory: 'coverage',
coverageThreshold: {
global: {
branches: 70,
functions: 80,
lines: 80,
statements: 80,
},
},
};When you run jest, if any metric falls below the threshold, Jest exits with a non-zero exit code—failing the CI build:
Jest: "global" coverage threshold for branches (70%) not met: 65%Coverage Metrics Explained
// Example function to illustrate each metric
function processOrder(order) { // function coverage: was this function called?
const total = order.items // statement coverage: was this line executed?
.reduce((sum, item) => {
return sum + item.price; // branch coverage: was this branch of reduce taken?
}, 0);
if (order.discount) { // branch: was the if-true branch taken?
return total * (1 - order.discount); // statement: executed when discount exists
}
return total; // branch: was the if-false branch taken?
}| Metric | What It Measures | Tricks |
|---|---|---|
| Lines | Was each line of code executed? | Similar to statements; easier to game |
| Statements | Was each statement executed? | More granular than lines; multi-statement lines count separately |
| Branches | Was each code path taken? | if/else, ternary, logical &&/||, switch cases |
| Functions | Was each function called? | Catches dead functions; easiest to satisfy |
Branches are most valuable. A function with if (flag) { ... } else { ... } needs two tests to hit both branches—one with flag=true, one with flag=false.
Per-File Thresholds
Global thresholds can mask individual file degradation. Use per-file thresholds for critical modules:
// jest.config.js
module.exports = {
coverageThreshold: {
global: {
lines: 80,
branches: 70,
},
// Critical business logic must have higher coverage
'./src/payment/': {
lines: 95,
branches: 90,
},
// Specific high-value file
'./src/auth/jwt.js': {
lines: 100,
branches: 100,
functions: 100,
},
// Glob pattern for all model files
'./src/models/*.js': {
lines: 85,
branches: 80,
},
},
};Coverage Reporters
Configure how coverage is reported and stored:
module.exports = {
coverageReporters: [
'text', // Console output summary
'text-summary', // Brief summary at end of test run
'html', // Detailed HTML report in coverage/
'lcov', // For CI tools (SonarQube, Codecov, Coveralls)
'json', // Machine-readable JSON
'json-summary', // Summary JSON for threshold comparison scripts
'clover', // XML format for some CI integrations
],
};The html reporter generates a browsable report:
coverage/
├── index.html ← Overview with file list and coverage percentages
├── src/
│ ├── payment/
│ │ └── index.html ← File-level coverage with line-by-line highlighting
│ └── auth/
│ └── jwt.htmlCollecting Coverage from the Right Files
By default, Jest only collects coverage from files that are imported in tests. If a module is never imported, it won't appear in coverage at all.
module.exports = {
// Collect coverage from ALL source files, even untested ones
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'!src/**/*.d.ts', // Exclude TypeScript declaration files
'!src/**/index.{js,ts}', // Exclude barrel files (just re-exports)
'!src/**/*.stories.{js,tsx}', // Exclude Storybook stories
'!src/test-utils/**', // Exclude test utilities
],
};Without collectCoverageFrom, a file with 0 tests doesn't lower your coverage percentage—it's simply invisible. This leads to deceptively high coverage numbers.
CI Integration
# .github/workflows/test.yaml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- name: Run tests with coverage
run: npm test -- --coverage --coverageReporters=text-summary --coverageReporters=lcov
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
with:
files: coverage/lcov.info
fail_ci_if_error: true
token: ${{ secrets.CODECOV_TOKEN }}Coverage Badges in README
[](https://codecov.io/gh/org/repo)Excluding Code from Coverage
Some code shouldn't count against your coverage metrics:
// Generated code—exclude entire file
/* istanbul ignore file */
// Single branch not worth testing (error-only code path)
function parseConfig(input) {
try {
return JSON.parse(input);
} catch (e) {
/* istanbul ignore next */
throw new Error(`Invalid config: ${e.message}`);
}
}
// Specific branch
function getEnv(key) {
/* istanbul ignore next */
if (process.env.NODE_ENV === 'test' && testOverrides[key]) {
return testOverrides[key];
}
return process.env[key];
}Use exclusions sparingly. Every exclusion is a documented decision to not test something. If you find yourself excluding a lot of code, that's a signal to write more tests, not more exclusions.
Ratcheting Coverage Over Time
The ratchet pattern: start below current coverage, enforce it, then incrementally raise the threshold.
// Week 1: current coverage is 67%. Start at 65%.
coverageThreshold: { global: { lines: 65 } }
// Week 4: team has written new tests. Coverage at 72%. Raise threshold.
coverageThreshold: { global: { lines: 70 } }
// Week 8: coverage at 80%. Raise again.
coverageThreshold: { global: { lines: 78 } }You can automate this with a coverage tracking script:
// scripts/check-coverage-regression.js
const fs = require('fs');
const current = JSON.parse(fs.readFileSync('coverage/coverage-summary.json'));
const baseline = JSON.parse(fs.readFileSync('coverage/baseline.json'));
const currentLines = current.total.lines.pct;
const baselineLines = baseline.total.lines.pct;
if (currentLines < baselineLines - 1) { // Allow 1% drop
console.error(`Coverage regression: ${baselineLines}% → ${currentLines}%`);
process.exit(1);
}
console.log(`Coverage OK: ${currentLines}% (baseline: ${baselineLines}%)`);Common Mistakes
Mistake: Collecting coverage only from tested files. Fix: set collectCoverageFrom to include all source files.
Mistake: Setting thresholds too high immediately. Fix: start below current coverage, ratchet upward.
Mistake: Using line coverage only. Fix: add branch coverage thresholds—branches catch untested conditional logic that lines miss.
Mistake: Running coverage locally on every test run. Fix: set collectCoverage: false in jest.config.js, run with --coverage only in CI.
Mistake: Mistaking high coverage for good tests. Fix: coverage measures whether code was executed, not whether it was tested meaningfully. A test that calls a function but makes no assertions gives 100% coverage with zero quality guarantee.
Summary
Jest coverage thresholds turn coverage from a metric you look at occasionally into a quality gate that blocks degradation. Configure:
collectCoverageFromto include all source files- Global thresholds for lines, branches, functions
- Per-file thresholds for critical modules
lcovreporter for CI integration--coverageflag in CI, not by default locally
Then ratchet the thresholds upward over time as you add tests.