Cory Rylan

My name is , Google Developer Expert, Speaker, Software Developer. Building Design Systems and Web Components.

Follow @coryrylan
Angular

Enforcing Code Coverage in Angular CLI Projects

Cory Rylan

- 1 minute

Updated

This article has been updated to the latest version Angular 17 and tested with Angular 16. 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.

Twitter Facebook LinkedIn Email
 

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

Related Posts

Angular

Creating Dynamic Tables in Angular

Learn how to easily create HTML tables in Angular from dynamic data sources.

Read Article
Web Components

Reusable Component Patterns - Default Slots

Learn about how to use default slots in Web Components for a more flexible API design.

Read Article
Web Components

Reusable Component Anti-Patterns - Semantic Obfuscation

Learn about UI Component API design and one of the common anti-patterns, Semantic Obfuscation.

Read Article