Code Coverage with Istanbul/nyc in Mocha Projects

Code Coverage with Istanbul/nyc in Mocha Projects
  • nyc is the CLI wrapper for Istanbul — install it with npm install --save-dev nyc
  • Run with: nyc mocha (or npx nyc mocha) — nyc instruments your code transparently
  • Configure reporters, thresholds, and include/exclude patterns in .nycrc or package.json
  • Use --check-coverage to fail CI when coverage drops below defined thresholds
  • Branch coverage is stricter than statement coverage — both matter, but branch misses find real bugs

Code coverage tells you which lines, branches, functions, and statements your tests actually execute. A test suite with 95% coverage is not the same as one with 95% confidence — coverage measures reach, not correctness — but it is an indispensable signal for finding untested paths. Istanbul (and its CLI wrapper nyc) is the standard coverage tool for JavaScript projects. This post covers the full setup: installation, configuration, reporter choices, threshold enforcement, understanding what coverage metrics mean, and excluding code that should not count.

Installation and Basic Setup

Install nyc as a dev dependency:

npm install --save-dev nyc

Run it by prefixing your existing Mocha command:

npx nyc mocha
# or if you have mocha in package.json scripts:
npx nyc npm test

nyc instruments your source files at require-time using Istanbul's instrumentation, runs the test command as a child process, and then collects and reports coverage when the process exits. No changes to your source code or tests are needed.

Add a coverage script to package.json:

{
  "scripts": {
    "test": "mocha",
    "coverage": "nyc mocha"
  }
}

Configuration

nyc reads configuration from a .nycrc, .nycrc.json, or a nyc key in package.json. The .nycrc.json approach keeps it explicit:

// .nycrc.json
{
  "include": ["src/**/*.js"],
  "exclude": [
    "src/**/*.spec.js",
    "src/**/*.test.js",
    "src/migrations/**",
    "src/seeds/**"
  ],
  "extension": [".js", ".mjs"],
  "reporter": ["text", "html", "lcov"],
  "report-dir": "coverage",
  "all": true,
  "check-coverage": true,
  "branches": 80,
  "lines": 90,
  "functions": 90,
  "statements": 90
}

Key options explained:

  • include / exclude: Glob patterns controlling which files are instrumented. Without include, nyc instruments everything it encounters at require-time, which can include vendored code and generated files.
  • all: true: Report coverage for files that were never required during tests. Without this, a module with zero test coverage simply does not appear in the report — you cannot see the gap.
  • reporter: Which output formats to generate (covered in detail below).
  • check-coverage: When true, nyc exits with a non-zero code if any threshold is not met, causing CI to fail.
  • branches, lines, functions, statements: The threshold percentages for each metric.

Coverage Reporters

text (terminal output)

The default, printed to stdout after the test run:

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |   89.47 |    73.33 |   92.31 |   89.47 |
 src/     |         |          |         |         |
  auth.js |   95.24 |    83.33 |     100 |   95.24 | 47
  db.js   |   84.62 |    66.67 |   85.71 |   84.62 | 22-24, 38
----------|---------|----------|---------|---------|-------------------

The "Uncovered Line #s" column is the most actionable: those are the exact lines your tests never executed.

HTML

An interactive report in the coverage/ directory. Open coverage/index.html in a browser to see file-by-file coverage with line-by-line highlighting — green for covered, red for uncovered, yellow for partially covered branches.

lcov

The LCOV format is consumed by many CI coverage services: Coveralls, Codecov, SonarQube, and GitHub's code coverage UI. It produces coverage/lcov.info.

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

Upload to Codecov in CI:

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

text-summary

A compact one-line-per-metric summary, useful when you want coverage in CI logs without the full file table:

Stmts : 89.47% ( 102/114 )
Branch: 73.33% ( 22/30 )
Funcs : 92.31% ( 12/13 )
Lines : 89.47% ( 102/114 )

Coverage Thresholds and CI Gates

The check-coverage option turns coverage into a hard gate. When a threshold is breached, nyc exits with code 1 after printing a clear message:

ERROR: Coverage for branches (66.67%) does not meet global threshold (80%)

A typical threshold configuration for a mature codebase:

{
  "check-coverage": true,
  "branches": 80,
  "lines": 90,
  "functions": 90,
  "statements": 90
}

For a new project, start lower (50-60%) and ratchet thresholds up over time. Setting 90% on day one discourages shipping until tests exist, which is good; but an unreachable threshold discourages shipping at all, which is not.

You can set per-file thresholds separately from the global threshold:

{
  "per-file": true,
  "branches": 70,
  "lines": 80
}

With per-file: true, every individual file must meet the thresholds — a single untested file cannot hide behind high aggregate coverage.

Branch Coverage vs Statement Coverage

Statement coverage (or line coverage) answers: was this line executed at all? Branch coverage answers: was every decision point — every if, ternary, &&, ||, switch case — exercised in both the true and false paths?

Consider this function:

function discount(user, amount) {
  if (user.isPremium) {
    return amount * 0.8; // 20% off
  }
  return amount;
}

A test that only calls discount({ isPremium: true }, 100) achieves 100% statement coverage — both lines are executed. But branch coverage is 50% because the false branch of user.isPremium was never taken. The second test discount({ isPremium: false }, 100) is needed to hit 100% branch coverage.

Branch misses are where real bugs hide:

function getDisplayName(user) {
  return user.nickname || user.firstName + ' ' + user.lastName;
}

If tests only cover users with nicknames, the || user.firstName + ' ' + user.lastName path is never executed. A bug in that string concatenation (say, lastName can be undefined) would go undetected.

Always watch branch coverage, not just statement coverage. A 90% statement / 60% branch gap is a red flag that your error paths and conditional logic are untested.

Ignoring Code from Coverage

Some code should legitimately be excluded: vendor files, generated code, CLI entry points that are hard to unit-test, or defensive code that is theoretically unreachable.

File-level exclusion via .nycrc

{
  "exclude": [
    "src/cli.js",
    "src/generated/**",
    "src/vendor/**",
    "**/*.config.js"
  ]
}

Inline ignore comments

For individual lines or blocks:

/* istanbul ignore next */
function impossibleBranch() {
  // This path cannot be triggered through normal API usage
  throw new Error('Internal state corruption');
}

function parseInput(value) {
  if (typeof value === 'string') {
    return value.trim();
  }
  /* istanbul ignore next */
  // This branch exists only for TypeScript type safety; JS always reaches the if
  return String(value);
}

/* istanbul ignore next */ ignores the next statement, function, or branch. Use it sparingly — overuse means your coverage number is lying about how much code is actually protected.

For ignoring an entire file, add this comment at the top:

/* istanbul ignore file */

A Complete Example

Project structure:

src/
  userService.js
  emailService.js
test/
  userService.spec.js
  emailService.spec.js
.nycrc.json
.mocharc.js

.mocharc.js:

module.exports = {
  spec: 'test/**/*.spec.js',
  timeout: 10000,
  require: ['test/hooks/root.js'],
};

.nycrc.json:

{
  "include": ["src/**/*.js"],
  "exclude": ["src/**/*.spec.js"],
  "reporter": ["text", "html", "lcov"],
  "report-dir": "coverage",
  "all": true,
  "check-coverage": true,
  "branches": 80,
  "lines": 90,
  "functions": 90,
  "statements": 90
}

package.json scripts:

{
  "scripts": {
    "test": "mocha",
    "coverage": "nyc mocha",
    "coverage:ci": "nyc mocha && nyc report --reporter=lcov"
  }
}

GitHub Actions step:

- name: Test with coverage
  run: npm run coverage:ci

- name: Check coverage thresholds
  run: npx nyc check-coverage

- name: Upload lcov to Codecov
  uses: codecov/codecov-action@v4
  with:
    files: ./coverage/lcov.info

ES Modules and TypeScript

If you use ES modules ("type": "module" in package.json), nyc needs --experimental-vm-modules and some additional configuration:

{
  "scripts": {
    "coverage": "node --experimental-vm-modules node_modules/.bin/nyc mocha"
  }
}

For TypeScript projects, use ts-node and configure nyc to handle .ts extensions:

npm install --save-dev @istanbuljs/nyc-config-typescript ts-node
{
  "extends": "@istanbuljs/nyc-config-typescript",
  "include": ["src/**/*.ts"],
  "extension": [".ts"]
}

Summary

nyc (Istanbul) integrates with Mocha through a simple prefix — no changes to tests or source code required. Configure it once in .nycrc.json: set include to scope instrumentation to your source, enable all: true so zero-coverage files appear in the report, choose text, html, and lcov reporters to cover terminal feedback, human review, and CI integration respectively. Enforce thresholds with check-coverage to make coverage a genuine CI gate rather than an informational metric. Pay particular attention to branch coverage — it catches the conditional logic gaps that statement coverage misses. Use /* istanbul ignore next */ for genuinely unreachable defensive code, but treat any widespread use as a sign that the architecture needs review.

Read more

Start now free