Istanbul / NYC Code Coverage: Setup, Reporters, and Thresholds
Code coverage is one of those metrics that teams either obsess over or ignore entirely. Neither extreme serves you well. Istanbul — the instrumentation engine that powers NYC, Jest's built-in coverage, and dozens of other tools — gives you the data to make informed decisions about where your test suite has gaps. This guide covers everything from initial setup to enforcing coverage gates in CI.
What Istanbul Actually Measures
Istanbul instruments your JavaScript or TypeScript source files by wrapping statements, branches, functions, and lines with counters. When your tests run, those counters increment. At the end, Istanbul produces a report showing what percentage of each category was exercised.
The four metrics you'll see in every report:
- Statements: individual executable statements
- Branches: each possible path through conditionals (
if/else, ternary,switchcases) - Functions: every declared function or method
- Lines: physical lines of code containing at least one statement
Branch coverage is the most revealing. A function can be fully covered by statements yet have entire logical branches never reached if you only test the happy path.
Setting Up NYC with Mocha
NYC (Istanbul's command-line interface) works with any test runner. Install it alongside Mocha:
npm install --save-dev nyc mochaAdd a script to package.json:
{
"scripts": {
"test": "mocha 'src/**/*.test.js'",
"coverage": "nyc mocha 'src/**/*.test.js'"
}
}Configure NYC either in package.json or a .nycrc.json file. The dedicated config file keeps things clean:
{
"include": ["src/**/*.js", "src/**/*.ts"],
"exclude": ["src/**/*.test.js", "src/**/*.spec.js", "src/generated/**"],
"reporter": ["text", "lcov", "html"],
"all": true,
"check-coverage": true,
"branches": 80,
"functions": 85,
"lines": 85,
"statements": 85
}The all: true option is critical — without it, NYC only reports coverage for files that were actually imported during tests. Files with zero test coverage simply won't appear, making your numbers look better than they are.
Setting Up Coverage with Jest
Jest ships with Istanbul built in. Enable it in jest.config.ts:
import type { Config } from 'jest';
const config: Config = {
collectCoverage: true,
collectCoverageFrom: [
'src/**/*.{ts,tsx}',
'!src/**/*.d.ts',
'!src/**/*.stories.{ts,tsx}',
'!src/generated/**',
'!src/index.ts',
],
coverageReporters: ['text', 'lcov', 'html', 'json-summary'],
coverageDirectory: 'coverage',
coverageThresholds: {
global: {
branches: 80,
functions: 85,
lines: 85,
statements: 85,
},
},
};
export default config;You can also set per-file thresholds, which is useful for critical modules:
coverageThresholds: {
global: {
branches: 75,
lines: 80,
},
'./src/auth/': {
branches: 95,
lines: 95,
},
'./src/payment/': {
branches: 90,
lines: 90,
},
},Understanding Coverage Reporters
Istanbul supports multiple output formats simultaneously. Each serves a different audience.
text — Prints a summary table directly to your terminal. Good for quick local checks.
------------------------|---------|----------|---------|---------|
File | % Stmts | % Branch | % Funcs | % Lines |
------------------------|---------|----------|---------|---------|
All files | 87.32 | 79.41 | 91.66 | 87.12 |
src/ | | | | |
auth.ts | 92.30 | 85.71 | 100.00 | 92.30 |
payment.ts | 78.94 | 66.66 | 83.33 | 78.94 |
utils.ts | 96.00 | 90.00 | 100.00 | 96.00 |html — Generates an interactive report in coverage/index.html. Each file shows highlighted source code with uncovered lines in red and partially covered branches in yellow. This is the most useful format for understanding what to test next.
lcov — Produces coverage/lcov.info, the standard format consumed by tools like Codecov, Coveralls, and SonarQube. Always enable this for CI pipelines.
json-summary — Outputs coverage/coverage-summary.json with machine-readable totals. Useful for custom scripts or badge generation.
Ignoring Files and Lines
Not everything needs coverage. Generated code, type declaration files, and configuration modules clutter your reports without adding signal.
Exclude entire directories in your NYC or Jest config as shown above. For individual lines or blocks, use Istanbul comments:
/* istanbul ignore next */
function legacyFallback() {
// This path is intentionally unreachable in modern environments
return null;
}
function processData(input: string | null) {
if (!input) {
/* istanbul ignore next */
throw new Error('Input required'); // defensive check, never null in practice
}
return input.trim().toLowerCase();
}Use these sparingly. Every ignored line is a judgment call that your future self needs to justify. A pattern of heavy ignores usually means your code is hard to test, not that the tests are unnecessary.
Enforcing Thresholds in CI
Coverage thresholds are useless unless they block the build. With NYC, the check-coverage flag causes a non-zero exit code when thresholds aren't met:
# .github/workflows/test.yml
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'
- run: npm ci
- run: npm run coverage
- uses: actions/upload-artifact@v4
if: always()
with:
name: coverage-report
path: coverage/With Jest, the coverageThresholds config automatically fails the test run if any threshold is missed — no additional CI configuration needed.
A common CI pattern is to start with achievable thresholds (say, 70%) and ratchet them up by 5% each quarter. This avoids the "add /* istanbul ignore */ everywhere to make the build pass" anti-pattern that emerges when teams set aspirational numbers on legacy codebases.
Tracking Branch Coverage Gaps
The text reporter's "Uncovered Line #s" column tells you which lines to focus on, but the HTML report makes branch gaps visible. Open coverage/index.html after a run, click into a file, and look for yellow highlighting — that's an if or ternary where only one branch was tested.
A typical gap pattern in TypeScript:
export function formatCurrency(amount: number, currency = 'USD'): string {
if (amount < 0) { // branch: negative amount — often untested
return `(${Math.abs(amount).toFixed(2)})`;
}
return `${currency} ${amount.toFixed(2)}`;
}The fix is a simple additional test case:
it('formats negative amounts with parentheses', () => {
expect(formatCurrency(-42.5)).toBe('(42.50)');
});Incremental Coverage for Large Codebases
On large codebases, global thresholds can mask local problems. A new feature with 30% coverage gets hidden behind a legacy codebase at 85%. Some teams solve this with per-directory thresholds. Another approach is diffCoverage — only measuring coverage on changed files in a PR. Tools like jest --changedSince or Codecov's patch coverage report support this workflow.
For monorepos with Turborepo or Nx, run coverage per package and aggregate with a tool like nyc merge:
# Merge individual package coverage reports
nyc merge coverage/packages coverage/.nyc_output/merged.json
nyc report --reporter=text --reporter=lcovCode coverage won't catch every bug, but consistent threshold enforcement prevents coverage from eroding as a codebase grows. The goal isn't 100% — it's meaningful coverage of the code paths that actually matter.