Get Coverage Report From Angular With Cypress
In my previous post, I talk how you can get coverage report with selenium.
If you remember, you have instrumented the application, well now I have implemented with angular.
Basically works on the same way, you have to instrument the application with angular, and then get the window.__coverage__
populated. For getting the coverage report.
Actually I’m working with cypress+angular+nestjs it’s a OOP combo because all can handle ts with object-oriented.
Let’s jump in.
Instrument Angular
If you were working with recent versions of angular, you know how the angular works.
You run:
npx ng serve
✔ Compiled successfully.
✔ Browser application bundle generation complete.
Initial Chunk Files | Names | Raw Size
runtime.js | runtime | 7.21 kB |
4 unchanged chunks
Then you get your application getting up and running behind the port http://localhost:4200 for example.
And that because the is using internally webpack to transpile your typescript code and convert it to JS and create multiple files to be served like static files.
Well, here is where you have to put something when the webpack is transpiling the code to JS, get the code instrumented.
Natively angular doesn’t support this; you need to extend the webpack to transpile getting instabul on it.
There are two options to apply this is using:
plus (npm install):
- babel-loader
- babel-plugin-istanbul
Both have the same objective, extends the webpack configuration. For instrument the code with istanbuljs.
// angular.json
"serve-cov": {
"builder": "ngx-build-plus:dev-server",
"configurations": {
"development": {
"browserTarget": "app:build:development"
}
},
"defaultConfiguration": "development",
"options": {
"extraWebpackConfig": "./coverage.webpack.js"
}
},
// coverage.webpack.js
module.exports = {
module: {
rules: [
{
test: /\.ts$/,
use: {
loader: "babel-loader",
options: {
plugins: ["babel-plugin-istanbul"],
},
},
enforce: "post",
include: require("path").join(__dirname, "src"),
exclude: [/node_modules/, /cypress/, /\.(e2e|spec)\.ts$/, /\.json$/],
},
],
},
};
Then you can execute:
npx ng run serve-cov
Will be up and running the ng serve
but instrumented with window.__coverage__
Then execute the cypress with coverage
npm i --save @cypress/code-coverage
npx cypress run --config baseUrl=http://localhost:42000
And you get the coverage report
Some examples based is: