Adding Code Coverage to Cypress Component Testing in Angular (And Loving It!)
Adding Code Coverage to Cypress Component Testing in Angular (And Loving It!)
Alright, fellow developers, let's talk about making Cypress component testing code coverage even better! If you've ever wondered whether your tests actually cover all the critical parts of your Angular components (including logic hidden in templates), then you're in the right place.
We went through the setup process, learned a few lessons, and now we’re here to help you do it in the smoothest way possible. Let's make it work, step by step!
Why Add Code Coverage?
Cypress component testing code coverage is like a flashlight for your tests. It highlights what parts of your code are covered and, more importantly, what parts are not.
For component testing in Cypress, it goes beyond just TypeScript functions—it even checks conditions inside your HTML templates. That means: no more unnoticed *ngIfs and *ngFors that could be skipping key logic!
How It Works
By default, Cypress doesn’t track Cypress component testing code coverage for Angular components. Unlike end-to-end testing where the app is fully bundled, component tests run in a Webpack-powered dev server. This means we need to instrument our code so Cypress can analyze what gets executed.
That’s where Babel and Istanbul step in. Babel helps inject coverage tracking into our TypeScript and HTML logic, and Istanbul collects the data. Let’s set it up!
Step 1: Install Dependencies
First, install the necessary packages:
npm install --save-dev @cypress/code-coverage babel-loader babel-plugin-istanbul @babel/core @babel/preset-env
This ensures that Cypress can track and report Cypress component testing code coverage correctly.
Step 2: Configure Babel
Create a babel.config.json
file in your project root and add:
{
"plugins": ["istanbul"]
}
Istanbul is the coverage tool, and Babel translates our code so Cypress can analyze it properly.
Step 3: Set Up Webpack for Coverage Instrumentation
Since Cypress component testing uses a Webpack dev server, we need to configure it to apply the Babel transformation. Create a file cypress/coverage.webpack.js
and add:
module.exports = {
module: {
rules: [
{
test: /\.(ts|js)$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['istanbul']
}
},
enforce: 'post',
exclude: /node_modules|cypress\/support|cypress\/e2e|\.spec\.ts$|\.cy\.ts$/
}
]
}
};
This ensures that all component logic, including Angular templates, is instrumented for Cypress component testing code coverage tracking.
Step 4: Update Cypress Configuration
Modify cypress.config.ts
to use the coverage Webpack setup:
```js import { defineConfig } from 'cypress'; import coverageWebpack from './cypress/coverage.webpack.js';
export default defineConfig({ component: { devServer: { framework: 'angular', bundler: 'webpack', webpackConfig: coverageWebpack, }, specPattern: 'src/**/*.cy.ts', setupNodeEvents(on, config) { require('@cypress/code-coverage/task')(on, config); return config; }, }, viewportWidth: 800, viewportHeight: 500, }); ```
Step 5: Enable Coverage Support in Tests
Add this to cypress/support/component.ts
:
```js import '@cypress/code-coverage/support';
Cypress.on('window:before:load', (win: any) => { win.coverage = win.coverage || {}; }); ```
This ensures that Cypress collects coverage data from each test run.
Step 6: Run Tests Before Generating Coverage Reports
Before you can generate a coverage report, you need to run your Cypress tests to collect coverage data.
Run your component tests as usual:
npx cypress run --component
Once the tests have completed, the coverage data will be collected and stored in the .nyc_output
directory.
Now, you can move on to generating reports.
Step 7: Reporting Coverage Data
To visualize your coverage results, you can generate reports in different formats:
npx nyc report --reporter=html # Generates an interactive HTML report
npx nyc report --reporter=text-summary # Outputs a summary in the console
npx nyc report --reporter=lcov # Generates LCOV data (for integration with CI tools)
Step 7: CI Integration
Automating coverage in a Continuous Integration (CI) pipeline ensures that every commit meets your testing standards. Here’s how you can integrate it:
- GitHub Actions: Add a job to run Cypress tests and collect coverage.
- Jenkins: Use a step to execute
npm run component-tests-coverage
and store results. - SonarQube: Upload LCOV reports for in-depth analysis.
Frequently Asked Questions (FAQ)
1. What does code coverage mean for component tests?
Code coverage measures which parts of your code are executed by tests. For Cypress component tests, this includes:
- TypeScript logic → Methods in
.ts
files such asngOnChanges()
- HTML template logic →
*ngIf
,*ngFor
,@Input()
, and other Angular bindings
2. Why is my coverage percentage so low?
- Check if your Cypress component tests cover all functionality.
- Review the report to see which lines are not covered.
- Ensure Webpack instrumentation is set up correctly.
3. How do I achieve 100% coverage in all columns?
The report provides different metrics:
- Statements → Are all code blocks executed?
- Branches → Are all
if/else
andswitch
cases tested? - Functions → Are all methods called?
- Lines → Are all lines in the files tested?
4. This report covers .ts
files, how do I know if HTML logic is included?
Code coverage tools also track HTML bindings and directives since they are processed through TypeScript.
5. Why do I see uncovered lines even though my test calls them?
- Are you testing a function but not all possible inputs?
- Are there hidden paths in an
if
statement?
6. Can I merge coverage reports from multiple projects?
Yes! Use nyc merge
to combine coverage from all projects:
npx nyc merge "apps/**/.nyc_output" "libs/**/.nyc_output" "coverage/.nyc_output"
7. How do I ensure Jest coverage is not mixed with Cypress coverage?
- Both Cypress and Jest generate a
.nyc_output
directory. - In
.nycrc
, you can configure it to only include Cypress coverage.
Learn More
For more details, check out the official Cypress documentation on code coverage:
Read more about Cypress Code Coverage
Looking for more insights on frontend development, testing, and best practices? Check out our other blog posts at Divotion Blog.