Cory Rylan

My name is . Google Developer Expert, speaker, and Software Developer at VMware Clarity Design System.

Follow @coryrylan

Enforcing Code Coverage in Angular CLI Projects

Cory Rylan

- 1 minute


This article has been updated to the latest version Angular 12 and tested with Angular 11. The content is likely still applicable for all Angular 2 + versions.

In this short post, we will cover unit testing code coverage. Unit testing is an important aspect of large-scale Angular applications. With the
Angular CLI its easy to test, run coverage reports and enforces a minimum coverage for the project.

To run our unit tests and generate our report run the following code:

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

Once ran the unit tests will run a single time reporting any issues. If all tests pass, we will see a new /coverage folder generated. In the coverage folder, we can simply double click the index.html file in our finder/file explorer and view the report in the browser. You should see something similar to the following:

Angular Code Coverage

So now that we have unit tests and code coverage, we can enforce an absolute minimum to be tested. This minimum is up to your team to decide, but I usually try to make a goal of 80% or more.

To enforce this as a build error if our coverage drops below 80% we need to edit our karma.conf.js file. In this file under the coverageIstanbulReporter key we add the following:

coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true,
thresholds: {
statements: 80,
lines: 80,
branches: 80,
functions: 80

Under thresholds we can tell Karma our test runner to have certain minimum thresholds for our code coverage. If our code coverage drops below these percentages, Karma will throw an error and fail the build. With the Angular CLI, we can get fantastic tooling for our client-side applications.


No spam. Short occasional updates on Web Development articles, videos, and new courses in your inbox.

Related Posts

VMWare Clarity

Building forms with Angular and Clarity Design

Learn how to create high-quality forms using Angular and the Clarity Design System.

Read Article

Using HTML5 Date Input with Date Objects and Angular

Learn how to use JavaScript Date Objects with the native HTML5 datepicker and Angular Forms.

Read Article

Measuring Angular Performance with Source Map Explorer

Learn how to identify performance bottlenecks in your Angular application with the Source Map Explorer tool.

Read Article