Getting coverage reports with Angular

This artical is basically an extension to the previous post: Improving Angular Style and Code Quality and mashed up with: Better together: SonarQube, TypeScript and Code Coverage

In short: we add SonarQube static analysis to our Angular CLI project and enable code coverage reports.


Enable code coverage

If you have used the CLI to generate your Angular project, there is a karma.conf.js file in your source directory which is already properly configured. SonarQube expects us to upload a file in a LCOV format, so we depend on the correct report format:

// karma.conf.js
// ....

coverageIstanbulReporter: {
  dir: require('path').join(__dirname, '../coverage'),
  reports: ['html', 'lcovonly'],
  fixWebpackSourcePaths: true

// ....

Now, there are a couple of ways to enable the generation of code coverage reports. The simplest way is to provide an extra CLI paramter:

ng test --watch=false --code-coverage

But usually, the best way is to ensure code coverage reports by default. This is easily achieved by editing the angular.json file in your project root directory:

// angular.json
// ....

"options": {
  "codeCoverage": true,
  "main": "src/test.ts",

// ....

If we now run our tests, we should see coverage files being created in the project\coverage directory. This directory now contains html files for local inspection and a single ‘’ file we can upload to SonarQube.


Add SonarQube

We add SonarQube (or SonarSource, the cloud service) simply by adding a local scanner. But to enable TypeScript code coverage support, we also need to add the SonarTS plugin:

npm install tslint-sonarts --save-dev
npm install sonar-scanner --save-dev

To configure the Sonar scanner, we make use of the file in the root of our project. In this file we need a couple of properties, depending on your scenario (on premises, SonarCloud):

Note: if we run the scanner, it will create a local .scannerwork directory in your project folder. You probably want to exclude this directory from source control and add this directory to your .gitignore file.

Running our sonar scanner should should produce our code coverage data in SonarQube. The easiest way of running the scanner is through the use of a npm script entry: “sonar”: “sonar-scanner”

npm run sonar


You can grab the sources mentioned here (and the test project) from the GitHub repo: