0
0
Node.jsframework~5 mins

Code coverage basics in Node.js

Choose your learning style9 modes available
Introduction

Code coverage shows how much of your code is tested by your tests. It helps find parts of code that need more testing.

When you want to check if your tests cover all important parts of your code.
Before releasing software to make sure critical code is tested.
When adding new features to ensure new code is tested.
To find unused or dead code that can be cleaned up.
When improving test quality and reliability.
Syntax
Node.js
npx nyc node your_test_file.js

# or with npm scripts
"scripts": {
  "test": "nyc mocha"
}

nyc is a popular tool to measure code coverage in Node.js.

You run your tests with nyc to collect coverage data automatically.

Examples
Run a single test file with coverage using nyc.
Node.js
npx nyc node test.js
Add a test script in package.json to run tests with coverage.
Node.js
"scripts": {
  "test": "nyc mocha"
}
Run tests and generate an HTML report showing coverage details visually.
Node.js
npx nyc --reporter=html mocha
Sample Program

This simple Node.js script has two functions and tests for both. Running it with nyc will show coverage for add and multiply.

Node.js
const assert = require('assert');

function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

// Simple tests
assert.strictEqual(add(2, 3), 5);
assert.strictEqual(multiply(2, 3), 6);

console.log('Tests passed');
OutputSuccess
Important Notes

Code coverage does not guarantee your code is bug-free, only that tests run those parts.

Try to cover important logic and edge cases in your tests for better quality.

Use coverage reports to find untested code and add tests there.

Summary

Code coverage measures how much code your tests run.

Use tools like nyc to collect coverage in Node.js projects.

Coverage helps improve test quality and find missing tests.