Cory Rylan

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

Follow @coryrylan
Angular

Enforcing Code Coverage in Angular CLI Projects

By Cory Rylan

- 1 minute

Updated

Angular APIs may have changed since this article was published. Check the current Angular documentation when using its examples.

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.

Bluesky Facebook LinkedIn Email
 

Related Posts

Angular

Angular ngFor syntax

A introduction tutorial on how to use the Angular ngFor syntax in component templates to construct lists dynamically.

Read Article
Angular

Angular Observable Data Services

A tutorial on how to use Observables and how they can improve your Angular data services and managing state in your applications.

Read Article
Angular

Angular Form Builder and Validation Management

Learn about the new FormBuilder service and create a custom component to manage form validation in Angular components.

Read Article