Angular 2 code test coverage

Looking to calculate the code coverage of my Angular 2 code. Wondering if there are any plugins available for VS Code or WebStorm that can assist with this. My unit testing is done using Jasmine and Karma.

Answer №1

To view comprehensive test coverage statistics in Angular CLI, simply enter the following command at the bottom of your command prompt window:

ng test --code-coverage

Result:

https://i.stack.imgur.com/2wo3O.png

If you wish to see the individual test coverage of components, follow these steps:

  1. npm install --save-dev karma-teamcity-reporter

  2. Add

    require('karma-teamcity-reporter')
    to the list of plugins in karma.conf.js

  3. ng test --code-coverage --reporters=teamcity,coverage-istanbul

Note that the list of reporters is comma-separated, with the addition of a new reporter, teamcity.

After running this command, navigate to the coverage folder in your directory and open index.html for a graphical representation of test coverage.

https://i.stack.imgur.com/luaq2.png

In addition, you can specify the desired coverage threshold in karma.conf.js as follows:

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

Answer №2

To begin, start by installing the necessary dependencies.

npm install karma karma-jasmine karma-chrome-launcher karma-jasmine-html-reporter karma-coverage-istanbul-reporter

Next, execute the ng test command.

ng test --code-coverage

Afterwards, run the server to view your coverage report.

http-server -c-1 -o -p 9875 ./coverage

You'll see a display similar to this:

https://i.stack.imgur.com/FfNdx.png

If you're interested, I've written a blog post on this topic here.

Answer №3

This one had me stumped for a while. After some trial and error, I finally found the solution:

ng test --code-coverage

Just double-check that your karma.conf.js file includes a specified reporter (I personally prefer 'coverage-istanbul')

For example: reporters: ['coverage-istanbul']

You'll find the coverage report in a folder named 'coverage' at the root of your directory.

Answer №4

Running ng test with code coverage enabled: 

Alternatively, you can run ng test with additional reporters for TeamCity and Istanbul coverage:

ng test --code-coverage --reporters=teamcity,coverage-istanbul

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind the command "npm-install" placing files directly into the root directory?

After pulling my front-end project from the repository, I noticed that the node_modules folder was missing. My usual approach is to use npm install to get all the dependencies listed in the package.json file installed. However, this time around, I ended u ...

Observing changes in the DOM using Angular

Is there a way to programmatically track the changes of a DOM node? It can be time-consuming to detect the delta in the inspector, especially with angular components that have many class names. https://i.stack.imgur.com/ns6rR.png I am looking for a more ...

What is the reason behind decorators needing to utilize apply(this) on a function?

I've been delving into the realm of JavaScript and exploring decorator code. One thing I've noticed is that when looking at decorator code like the example below, the input function always applies to 'this' even though it doesn't a ...

Provider not found: ConnectionBackend – NullInjectorError

I encountered the following error while attempting to load the webpage. Despite trying various suggestions from other sources, I have been unable to find a solution. Below the error stack lies my code. core.js:7187 ERROR Error: Uncaught (in promise): Null ...

Developing a custom package containing personally crafted type definitions and importing them into the project

I'm in need of creating a private npm package specifically for custom type definitions (typedefs) that are hand-written d.ts files not generated by TypeScript. Since these are proprietary, they cannot be added to DefinitelyTyped. The folder structure ...

Extracting information from console output and displaying it in a table with angular2

https://i.stack.imgur.com/BMt6J.pngI am facing an issue with retrieving data from the console output and populating it into an HTML table. Can someone please assist me with this? Here is the HTML Code: <table class="table"> <tr> <t ...

A comprehensive guide on implementing form array validations in Angular 8

I am currently using the formArray feature to dynamically display data in a table, which is working perfectly. However, I am facing difficulty in applying the required field validation for this table. My goal is to validate the table so that no null entry ...

Setting attributes within an object by looping through its keys

I define an enum called REPORT_PARAMETERS: enum REPORT_PARAMETERS { DEFECT_CODE = 'DEFECT_CODE', ORGANIZATION = 'ORGANIZATION' } In addition, I have a Form interface and two objects - form and formMappers that utilize the REPOR ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

What is the method for typing an array of objects retrieved from realmDB?

Issue: Argument type 'Results<Courses[] & Object>' cannot be assigned to the parameter type 'SetStateAction<Courses[]>'. Type 'Results<Courses[] & Object>' lacks properties such as pop, push, reverse, ...

What is the best way to compress a file for transfer to a server using gzip?

While attempting to upload a file and send it to the server via a REST API, I am looking for a reliable method to gzip the file. Unfortunately, there is limited documentation available on this topic. Can anyone suggest the most effective approach to achiev ...

Integrating Octokit middleware in Next.js for enhanced functionality

Currently, I am in the process of honing my skills by creating a GitHub app. In Octokit, there is a feature called createNodeMiddleware that caught my attention. However, integrating it with next.js seems to pose some challenges. My main issue right now re ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Embedding content within various ng-template elements

I'm currently working on developing a button component (app-button) that can utilize multiple templates based on the parent component using it. <div class="ds-u-margin-left--1 ds-u-float--left"> <ng-container *ngTemplateOutlet="icon">< ...

Issue with Angular data display in template

My Ionic app with Angular is fetching data in the constructor, but I am facing difficulties displaying it in the HTML. Code component receiver: any; constructor( //.... ) { // get receiver data const receiverData = this.activatedRoute.snapsho ...

Limiting the assignment of type solely based on its own type, without considering the components of the type

I have defined two distinct types: type FooId = string type BarId = string These types are used to indicate the specific type of string expected in various scenarios. Despite TypeScript's flexibility, it is still possible to perform these assignment ...

CSS-WHAT Package for Angular Update - Enhance Your Styles!

In my Angular setup, the configurations are as follows: _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | ...

Vitek - Uncaught ReferenceError: Document Is Not Defined

Why am I encountering an error when trying to use File in my vitest code, even though I can typically use it anywhere else? How can I fix this issue? This is the content of my vite.config.ts. /// <reference types="vitest" /> import { defin ...

Using Long Polling with Angular 4

I am looking for a way to monitor the progress of a certain task using API calls. To achieve this, I have developed a service that executes these API calls every 1.5 seconds Main Component private getProgress() { this.progressService.getExportPr ...

A guide on converting JSON to TypeScript objects while including calculated properties

I have a standard JSON service that returns data in a specific format. An example of the returned body looks like this: [{ x: 3, y: 5 }] I am looking to convert this data into instances of a customized TypeScript class called CustomClass: export class ...