Learn Angular 14 Unit testing code coverage using Karma

Angular CLI can run unit tests and create code coverage reports for your angular projects. You can find how much code has been covered in your files and project using karma. Code coverage reports can show you any parts of your code base that are tested and not covered by your unit tests.

You can generate code coverage by running this command ng test --no-watch --code-coverage

This will create a new /coverage folder in your project.

You also need to add this option in angular.json:

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

To set code coverage threshold you need to enable this in your Karma configuration file, karma.conf.js, by adding the check property in the coverageReporter:

coverageReporter: {
  check: {
    emitWarning: false,
    global: {
      statements: 50,
      branches: 50,
      functions: 50,
      lines: 50,
      excludes: [
        'app/bar/**/*.ts'
      ]
    },
    each: {
      statements: 50,
      branches: 50,
      functions: 50,
      lines: 50,
      excludes: [
        'app/directory/**/*.ts'
      ],
    }
  }
}
 

check is used to configure minimum threshold enforcement for coverage results. If the thresholds are not met, karma will fail the test.

Code Coverage Report

Image

Code Coverage of a file

Image

For more details please refer to this link - Angular

For Karma configuration details - Karma configuration