Skip to content

How to Record Test Coverage for JavaScript and TypeScript NodeJS Applications

This article describes how test coverage information can be recorded for a NodeJS application using IstanbulJS. It applies both to JavaScript and TypeScript applications. It can be used for all types of tests, including unit tests, automated E2E tests and manual tests.

For frontend JavaScript/TypeScript code, please use our tutorial for coverage in the browser.

Install Dependencies

bash
npm install --save-dev nyc

For a TypeScript application also run:

bash
npm install --save-dev @istanbuljs/nyc-config-typescript

Tests outside the CI/CD pipeline

Please note that if you are bundling your application and executing your tests on another system, e.g. a dedicated test environment, you will also need to install nyc in that environment. E.g. by running the following on the test environment:

bash
npm install -g nyc

TypeScript: Configure IstanbulJS

Create .nycrc in your project's root folder (next to package.json):

json
{
    "extends": "@istanbuljs/nyc-config-typescript"
}

Tests outside the CI/CD pipeline

Please note that if you are bundling your application and executing your tests on another system, e.g. a dedicated test environment, you will also need to copy .nycrc to that environment.

Enable Source Maps

For TypeScript or if you use a bundler/minifier to transform/package your JS code: enable source maps for all build steps. Make sure that each step contributes to the same source map, otherwise the recorded coverage will reference incorrect line numbers.

javascript
// tsconfig.json
{ compilerOptions: { sourceMap: true, ... }, ... }

See the Typescript documentation for more details and options.

Tests outside the CI/CD pipeline

Please note that if you are bundling your application and executing your tests on another system, e.g. a dedicated test environment, you will also need to copy the generated source maps (.map files) to that system.

Run Your Application with Coverage Recording

Run your application with nyc prepended to enable coverage recording at runtime:

bash
nyc --reporter=cobertura node src/index.js

Once your application shuts down, nyc generates the file coverage/cobertura-coverage.xml which contains the coverage information.

Upload Coverage to Teamscale

The final step is to upload this coverage file to Teamscale. This can be done by using the teamscale-upload tool with --format COBERTURA.

Troubleshooting

Teamscale shows the wrong or no lines as covered

Please check your source maps. These are used by nyc to map coverage data from your compiled JavaScript code back to the original source code. If the source maps are not correct, the coverage report will contain incorrect file names or line numbers.