tezvyn:

Code Coverage Reporting with nyc/Istanbul

AI-drafted, machine-checkedSource: github.comintermediate

Code coverage reporting asks, "Which lines of my code did my tests actually run?" Use a tool like `nyc` to wrap your test runner (e.g., Mocha) and generate a report. The footgun is chasing 100% coverage, which doesn't guarantee quality.

WHY IT EXISTS Code coverage tools were created to provide an objective measure of which parts of a codebase are exercised by a test suite. Without them, developers are just guessing how effective their tests are at covering different execution paths and edge cases.

THE MENTAL MODEL Think of code coverage reporting as a highlighter for your source code. After you run your tests, it highlights every line, branch, and function the tests touched. The un-highlighted code is your blind spot—code that could be broken without your tests ever noticing. It measures the quantity of execution, not the quality of your assertions.

HOW IT WORKS The Istanbul.js library, via its command-line interface nyc, instruments your JavaScript code. This means it injects counters into your source code before the tests run. As your tests execute, these counters are incremented. After the tests complete, nyc collects the data from these counters and generates a report showing what percentage of statements, branches, functions, and lines were executed. It supports source maps, so it works correctly with transpiled code from TypeScript or Babel.

WHEN TO USE IT Use nyc in your CI/CD pipeline to enforce a minimum coverage threshold and prevent regressions in test coverage. It's also useful during development to identify untested logic in new features. It integrates with most JavaScript test runners like Mocha or AVA by simply prefixing your test command, for example nyc mocha.

WHEN NOT TO USE IT Avoid using nyc if your test runner already has Istanbul.js integrated. For example, Jest and Tap provide code coverage reporting out of the box, so adding nyc is redundant. Also, don't use coverage as the sole metric for code quality; a line can be "covered" by a test that makes no meaningful assertions about its behavior.

ONE CANONICAL EXAMPLE To add coverage reporting to a project using Mocha, first install nyc as a dev dependency: npm install --save-dev nyc. Then, update your package.json scripts. If your test script is "test": "mocha", you would add a new script: "coverage": "nyc npm run test". Running npm run coverage will now execute your tests and generate a coverage report in the console and as an HTML file in a ./coverage directory.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.