Cypress code coverage
Cypress uses the @cypress/code-coverage (opens in a new tab) plugin to create repors. It uses istanbul (opens in a new tab) under the hood. See oficial Cypress code coverage (opens in a new tab) documentation for more details.
How to setup code coverage for React project with Webpack and ts-loader
The official documentation does not describe how to set up code coverage for the React project with Webpack and ts-loader. Here's how:
1. Install dependencies
npm install --save-dev @babel/core babel-loader babel-plugin-istanbul @cypress/code-coverage
2. Update webpack.config.js
Since ts-loader
works very well in combination with babel
and babel-loader
. (See ts-loader docs (opens in a new tab)). We can combine ts-loader
and babel-loader
together in Webpack settings.
export default {
// other settings
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: "babel-loader",
options: {
plugins: ["istanbul"],
},
},
"ts-loader",
],
},
],
},
// other settings
};
3. Update Cypress configuration
Add the code below to the support files:
import "@cypress/code-coverage/support";
import "@cypress/code-coverage/support";
Set up node events function:
import { defineConfig } from "cypress";
export default defineConfig({
// E2E Testing configuration. For more details, see:
// https://docs.cypress.io/guides/references/configuration#e2e
e2e: {
// other settings
setupNodeEvents(on, config) {
require("@cypress/code-coverage/task")(on, config);
return config;
},
},
// Component Testing configuration. For more details, see:
// https://docs.cypress.io/guides/references/configuration#component
component: {
// other settings
setupNodeEvents(on, config) {
require("@cypress/code-coverage/task")(on, config);
return config;
},
},
});
4. Check TypeScript configuration
đź’ˇ Make sure you have compilerOptions.sourceMap
set to true
in your cypress/tsconfgi.json
file. It is important! Otherwise, components code coverage won't work properly.
{
"extends": "../tsconfig.json",
"compilerOptions": {
// other settings
"sourceMap": true
}
}
And that's it! You can now run your Cyperss tests, and it'll give you a code coverage report. By default NYC (opens in a new tab) place a report in the coverage
folder and out.json
in .nyc_output
folder.