Hello everyone, I want to tell you how to add code coverage to an angular / react project. On the net you can find quite a few options for how to do this, and from my own experience I should note that sometimes with angular it is not so easy. Let's see how to add code coverage to version 11 of angular (if you have 7/8 ... this example may not work, better update)
Angular
Install all dependencies
npm i -D ngx-build-plus
npm i -D istanbul-instrumenter-loader
npm install -D @cypress/code-coverage
Moving from protractor to cypress
ng add @briebug/cypress-schematic
Create a cypress / coverage.webpack.js file
module.exports = {
module: {
rules: [
{
test: /\.(js|ts)$/,
loader: 'istanbul-instrumenter-loader',
options: { esModules: true },
enforce: 'post',
include: require('path').join(__dirname, '..', 'src'),
exclude: [
/\.(e2e|spec)\.ts$/,
/node_modules/,
/(ngfactory|ngstyle)\.js/
]
}
]
}
};
Let's update our angular.jso
"serve": {
"builder": "ngx-build-plus:dev-server",
"options": {
"browserTarget": "angular-registration-login-example:build",
"extraWebpackConfig": "./cypress/coverage.webpack.js"
}
},
Add to cypress / support / index.js
import '@cypress/code-coverage/support';
Add to cypress / plugins / index.js
module.exports = (on, config) => {
require('@cypress/code-coverage/task')(on, config)
// IMPORTANT to return the config object
// with the any changed environment variables
return config
}
Let's run the application, the console should have a window .__ coverage__ variable
After starting the application, all that remains is to run the tests npm run cy: open / cy: run
"cy:open": "cypress open",
"cy:run": "cypress run",
As soon as the tests pass, a coverage folder will be created in the root of the application.
You can see the result by opening the file coverage / lcov-report / index.html
By clicking on the components, you can see which code has been executed and how many times, and which has not yet been covered by tests
The project itself can be downloaded here: https://github.com/NikolayKozub/angular-coverage-cypress
React
Install all dependencies
npm i -D nyc
babel-plugin-istanbul
istanbul-lib-coverage
@cypress/code-coverage
@cypress/instrument-cra
Add to cypress / plugins / index.js
module.exports = (on, config) => {
require('@cypress/code-coverage/task')(on, config)
return config
}
Add to cypress / support / index.js
import '@cypress/code-coverage/support'
Add scripts to package.json
"start": "react-scripts start",
"start:coverage": "react-scripts -r @cypress/instrument-cra start",
Add .babelrc to the project root
{
"plugins": ["istanbul"]
}
We run tests and see the report