Istanbul/nyc: The Complete Code Coverage Guide for Node.js

Istanbul/nyc: The Complete Code Coverage Guide for Node.js

Code coverage without configuration is noise. You run nyc npm test, get a number, and have no idea whether that number reflects anything meaningful about your codebase. This guide fixes that.

Istanbul (the instrumentation library) and nyc (the CLI wrapper) are the standard tools for Node.js coverage. They've been around long enough to accumulate real-world battle scars, and understanding them properly means the difference between coverage that guides your testing and coverage theater.

Istanbul vs nyc: What You're Actually Using

Istanbul is the instrumentation engine. It transforms your source code, injecting counters at branches, statements, and functions. nyc is the CLI and reporter that wraps Istanbul, handling configuration, process spawning, and output formatting.

When you run nyc, you're using Istanbul under the hood. The two names get used interchangeably, but the package you install is nyc.

npm install --save-dev nyc

For modern projects using V8's built-in coverage (more on this below), you'll also want:

npm install --save-dev @istanbuljs/schema

Basic Setup

The minimal setup adds nyc to your test script:

{
  "scripts": {
    "test": "nyc mocha",
    "test:coverage": "nyc --reporter=html mocha"
  }
}

But running nyc bare gives you defaults that may not match your project. Configure it in package.json or a .nycrc file:

{
  "nyc": {
    "include": ["src/**/*.js"],
    "exclude": ["src/**/*.test.js", "src/generated/**"],
    "reporter": ["text", "html", "lcov"],
    "branches": 80,
    "lines": 85,
    "functions": 85,
    "statements": 85,
    "check-coverage": true
  }
}

The check-coverage: true flag makes nyc exit with a non-zero code when thresholds aren't met. This is what you use to fail CI builds.

V8 Coverage vs Istanbul Instrumentation

nyc's default approach instruments your source code — it rewrites every file to add counter increments. This works, but it has two problems: it's slow for large codebases, and source maps can get complicated.

V8's built-in coverage collects coverage data from the JavaScript engine directly, without rewriting source code. It's faster and produces more accurate results for modern JavaScript features.

Enable it:

{
  "nyc": {
    "instrument": false,
    "source-map": false
  }
}

And use the --experimental-vm-modules flag if you're on ESM:

node --experimental-vm-modules node_modules/.bin/nyc npm test

For TypeScript projects, V8 coverage combined with ts-node or pre-compiled output gives you accurate coverage without fighting with Istanbul's AST transformation:

{
  "nyc": {
    "extension": [".ts"],
    "require": ["ts-node/register"],
    "reporter": ["text", "html"],
    "sourceMap": true,
    "instrument": true
  }
}

nyc with Jest

Jest has its own coverage engine built on Istanbul, so if you're using Jest, you configure coverage in jest.config.js, not in nyc directly:

module.exports = {
  collectCoverageFrom: [
    'src/**/*.{js,ts}',
    '!src/**/*.test.{js,ts}',
    '!src/**/*.d.ts',
    '!src/generated/**',
  ],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 85,
      lines: 85,
      statements: 85,
    },
  },
  coverageReporters: ['text', 'html', 'lcov', 'json-summary'],
  coverageDirectory: 'coverage',
};

Run it:

jest --coverage

The json-summary reporter produces coverage/coverage-summary.json, which is what most CI integrations (Codecov, Coveralls) consume.

nyc with Mocha

Mocha doesn't have built-in coverage, so nyc wraps it directly:

nyc mocha --recursive test/**/*.spec.js

For async tests and complex setups, use a .mocharc.js:

module.exports = {
  require: ['test/setup.js'],
  recursive: true,
  timeout: 5000,
};

And wrap the whole thing:

{
  "scripts": {
    "test": "nyc --reporter=text --reporter=html mocha"
  }
}

One gotcha with Mocha: if you're spawning child processes in your tests, coverage from those processes won't be collected by default. Use nyc's --spawn option or configure NYC_CWD:

nyc --spawn npm test

Ignoring Coverage

Not every line needs coverage. Generated code, debug utilities, and platform-specific branches are legitimate candidates for exclusion.

Istanbul recognizes inline comments:

/* istanbul ignore next */
function debugOnlyHelper() {
  console.log('debug state:', JSON.stringify(state, null, 2));
}

function processInput(value) {
  if (value === null) /* istanbul ignore next */ {
    throw new Error('null not supported in legacy mode');
  }
  return transform(value);
}

For entire files, use the exclude configuration in .nycrc:

{
  "exclude": [
    "src/generated/**",
    "src/**/__mocks__/**",
    "src/utils/debug.js",
    "**/*.config.js"
  ]
}

The /* istanbul ignore if */ and /* istanbul ignore else */ variants let you ignore specific branches:

function handleError(err) {
  /* istanbul ignore if */
  if (process.env.NODE_ENV === 'development') {
    console.error('Full error:', err);
  }
  return { error: err.message };
}

Use these sparingly. Every ignore comment is a decision that the code isn't worth testing. If you're writing them frequently, you're papering over a design problem.

Per-File Thresholds

Global thresholds hide problems. A single well-tested utility file can drag up the global average, masking completely untested modules.

nyc supports per-file thresholds:

{
  "nyc": {
    "check-coverage": true,
    "per-file": true,
    "lines": 70,
    "branches": 60,
    "functions": 70,
    "statements": 70
  }
}

With per-file: true, every single file in your codebase must meet the thresholds. This is strict. A more practical approach is to use Jest's per-file threshold configuration for critical paths:

coverageThreshold: {
  global: {
    lines: 80,
  },
  './src/payments/**/*.js': {
    lines: 95,
    branches: 90,
  },
  './src/auth/**/*.js': {
    lines: 95,
    branches: 90,
  },
},

This enforces high standards where they matter — payment processing, authentication — without requiring the same rigor for configuration parsers or utility functions.

HTML Reports

The text reporter is fine for CI output. The HTML reporter is what you use when coverage drops and you need to understand why.

nyc --reporter=html npm test
open coverage/index.html

The HTML report shows you exactly which lines, branches, and functions were executed. Red highlights mean uncovered. Yellow means partially covered (one branch hit, the other not).

The most useful view is the branch coverage view. A line might be marked as covered because it executed, but if it contains a conditional, you might have only tested one path. The HTML report makes this visible.

For CI, generate lcov format alongside HTML:

{
  "nyc": {
    "reporter": ["text", "html", "lcov"]
  }
}

The lcov.info file in coverage/ is what Codecov, Coveralls, and SonarQube consume.

Caching and Performance

nyc caches instrumented files in node_modules/.cache/nyc. For large projects, this makes subsequent runs significantly faster. For CI, you want to cache this directory:

# GitHub Actions
- uses: actions/cache@v3
  with:
    path: node_modules/.cache/nyc
    key: nyc-cache-${{ hashFiles('package-lock.json') }}

Clear the cache when you see stale coverage data:

nyc clear-cache

A single coverage number tells you nothing about trajectory. Is coverage improving, stagnating, or declining? Tools like Codecov track this over time and can post coverage diffs directly to pull requests.

Basic Codecov integration after generating lcov:

# Install the Codecov uploader
npm install --save-dev codecov

# After tests
nyc report --reporter=lcov
npx codecov

In GitHub Actions:

- name: Upload coverage
  uses: codecov/codecov-action@v3
  with:
    files: ./coverage/lcov.info
    fail_ci_if_error: true

The coverage diff in PR comments shows exactly which lines added in the PR are covered and which aren't. This shifts the conversation from "what's our global coverage?" to "is this new code tested?"

The Number That Matters

nyc gives you four metrics: statements, branches, functions, and lines. Of these, branch coverage is the one that catches real bugs. A statement can execute without exercising the logic that makes it correct. A branch test verifies that both the true and false paths through your code are tested.

If you're going to pick one threshold to enforce strictly, make it branches. 80% branch coverage with thoughtful tests beats 95% line coverage with tests that just execute code paths without asserting outcomes.

The tool is correct. Make sure you're measuring what you think you're measuring.

Read more

Start now free