The Angular CLI can run unit tests and create code coverage reports. Code coverage reports show us any parts of our code base that might not be properly tested by our unit tests.

To generate a coverage report, let’s run the following command in the root of our project:

ng test --no-watch --code-coverage

When the tests are complete, the command creates a new /coverage directory in the project. Let us open the index.html file (inside the new directory) to see a report with our source code and code coverage values.

If we want to create code-coverage reports every time we test, let’s set the following option in the Angular CLI configuration file, angular.json:

"test": {
  "options": {
    "codeCoverage": true
  }
}

Code coverage enforcement

The code coverage percentages let us estimate how much of our code is tested. If in a team, we decides (in ourselves) on a set minimum amount to be unit tested, we can enforce this minimum with the Angular CLI.

For example, suppose we want the code base to have a minimum of 80% code coverage. To enable this, let’s open the Karma test platform configuration file, karma.conf.js, and add the check property in the coverageReporter: key.

coverageReporter: {
  dir: require('path').join(__dirname, './coverage/<project-name>'),
  subdir: '.',
  reporters: [
    { type: 'html' },
    { type: 'text-summary' }
  ],
  check: {
    global: {
      statements: 80,
      branches: 80,
      functions: 80,
      lines: 80
    }
  }
}

The check property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project. If the thresholds are not met, karma will return failure.

PS: Read more on coverage configuration options in the karma coverage documentation.

Step 2: Add SonarQube plugin to Karma.Conf

SonarQube will use the lcov.info file to get information about the typescript/javascript code quality. However, to map a TS/JS file with its Unit-Test file (Spec file) and make it understand coverage details, you need to use SonarQube plugin with Karma.

Let’s install the plugin

npm install -D karma-sonarqube-reporter

Head over to karma.conf.js and make the following changes:

//importing the modules
require('karma-sonarqube-reporter')

Add sonarqube to the array of reporters:

reporters:[‘progress’, ‘kjhtml’, ‘sonarqube’]

Configure Sonarqube in Karma.conf like this:

sonarqubeReporter: {
      basePath: 'src/app', // test files folder
      filePattern: '**/*spec.ts', // test files glob pattern
      encoding: 'utf-8', // test files encoding
      outputFolder: 'reports', // report destination
      legacyMode: false, // report for Sonarqube < 6.2 (disabled)
      reportName: function (metadata) {
        // report name callback, but accepts also a
        // string (file name) to generate a single file
        /**
         * Report metadata array:
         * - metadata[0] = browser name
         * - metadata[1] = browser version
         * - metadata[2] = plataform name
         * - metadata[3] = plataform version
         */
        return 'sonarqube_report.xml';
      },
    },

If we run ng test --code-coverage --watch=false now, there is a folder reports/ generated at the project root with sonarqube_report.xml file inside the folder.

Example of tree achitectur:

Install “sonar-scanner”

Now the time is to configuring the Sonar with Angular application and to do this we need sonar-scanner node package in the Angular application.

npm install -D sonarqube-scanner

The NPM package also has very good docs (https://www.npmjs.com/package/sonarqube-scanner). we can refer to it for further/more details.

Create a sonar-project.properties file in our project root

let’s Create a file called sonar-project.properties in our Angular root directory and add below attributes:

sonar.host.url=SONAR-QUBE-URL
sonar.projectKey=Project_Key # Must be unique (Primary key)
sonar.projectName=PROJECT_NAME # name that will be displayed on the dashboard
sonar.projectVersion=1.0
sonar.sourceEncoding=UTF-8
sonar.sources=src
sonar.exclusions=**/node_modules/**
sonar.tests=src # Where to pickup test files from
sonar.test.inclusions=**/*.spec.ts # only collect these for test-coverage
sonar.javascript.lcov.reportPaths=src/coverage/PROJECT_NAME/lcov.info
sonar.testExecutionReportPaths=reports/sonarqube_report.xml

Additionally, we can add the sonar.login and sonar.password if we have password-protected our SonarQube instance (Only when running locally!).

Integrate Karma code coverage with Sonarqube 

We have both Karma code coverage and Sonar server ready.

Now, let us integrate both using sonar-scanner.

First, add a script called sonar to your package.json,

"scripts": {
    "sonar": "sonar-scanner"
}

Finally, let’s run the below command to integrate the Karma coverage with the Sonar server,

npm run sonar

And we will see the result directly on the Sonar server by navigating to the corresponding url (setted previously to the sonar-project.properties file)

example:

Update our .gitignore file

Consider adding these items to our .gitignore file as they should not be tracked in version control.

PS: in our demo, the generated folder name is “reports” . so let us add it in the .gitignore file.

.scannerwork/*
reports/*  

Conclusion

To integrate karma test coverage with Sonarqube reporter , we have four important steps such as,

  1. Installing the Sonarqube.
  2. Configuring the Sonar with Angular using sonar-project.properties and installing the sonar-scanner package.
  3. Getting the Karma code coverage.
  4. Integrating the Karma code coverage with Sonarqube.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *