NodeJS by Example: Test Coverage
|
Test Coverage measures how much of your code is executed during tests. Node.js has built-in coverage reporting via the --experimental-test-coverage flag. |
|
|
Import test utilities |
|
|
Example Code to Test Here's a simple module we'll write tests for. |
|
|
Tests for Calculator Coverage is calculated based on which lines/branches are executed. |
|
|
Branch Coverage Coverage includes branches - if/else, switch cases, ternary operators. |
|
|
Line Coverage vs Branch Coverage A line can be covered but branches within it may not be. |
|
|
Testing Edge Cases Edge cases are important for both correctness and coverage. |
|
|
Async Code Coverage Coverage works with async code too. |
|
|
Understanding Coverage Reports The coverage report shows: - Line coverage: percentage of lines executed - Branch coverage: percentage of branches taken - Function coverage: percentage of functions called Example output: -------------------------------|---------|----------|---------|---------| File | % Stmts | % Branch | % Funcs | % Lines | -------------------------------|---------|----------|---------|---------| All files | 95.00 | 90.00 | 100.00 | 95.00 | test-coverage.js | 95.00 | 90.00 | 100.00 | 95.00 | -------------------------------|---------|----------|---------|---------| |
|
|
Excluding Code from Coverage Use /* c8 ignore */ comments to exclude code from coverage. |
|
|
Coverage Thresholds You can set minimum coverage thresholds in your CI/CD pipeline. If coverage falls below the threshold, the build fails. Example package.json script: "test:coverage": "node --test --experimental-test-coverage --test-coverage-branches=80 --test-coverage-lines=80" |
|
|
Run tests with coverage reporting |
|
|
Generate detailed coverage report |
|