See your Node.js project's tests' code coverage in two incredibly simple steps.

In 2019, doing Test Driven Development is the norm. Your project probably has tests, but do you know how much of your code is executed when the tests are ran?

That’s what code coverage is about. It’s a very useful measure to know which parts of the code are not reached by the tests. It’s not an absolute measure though, only an indicator. Parts of the code can be tested but still have bugs if the tests are not extensive enough.

Let’s see how to check the code coverage in a Node.JS project. We will use Istanbul via its CLI client, nyc.

npm i nyc --save-dev

Tt’s surprisingly simple to use. No config, just add nyc before your test command, for example:

$ npx nyc mocha

Or, in your package.json. Here is what’s in mine:

"scripts": {
    "start": "node ./bin/www",
    "test": "nyc mocha tests/*.test.js",
    "lint": "eslint ."

Here is the end of my npm test:

nyc outputs a nice table with each file and folder, with different units of coverage (lines, functions, etc). It even shows which line are not covered, for each file!

The reports are stored under .nyc_output/, so you might want to add that to your .gitignore.

Reports can be generated in other formats, such as HTML:

npx nyc report --reporter=html

Open ./coverage/index.html, and navigate trough an even more detailed report:

You can even browse your project and see which lines parts are not covered! This is simply amazing.

Personally, I run nyc for each testing pipeline for my project, so that I can see the code coverage evolution trough time. 👍