Use jest --coverage
to generate coverage report after testing. The report in HTML will be saved in ./coverage
directory. This directory should be included in .gitignore
.
The coverage report will include the test utilities as well, which makes no sense and affects the stats. We only want to know how well tested the application code is.
We can add collectCoverageFrom
to jest.config.js
.
module.exports = {
collectCoverageFrom: ["**/src/**/*.js"],
};
[!tip] Jest is excluding
__tests__
by default
The coverage report is generated by babel-plugin-istanbul
under the hood. It's possible to omit some parts in the coverage report with /* istanbul ignore next */
directive. However this is not recommended, as it's a kind of lying to yourself about how much of the code have been covered.
It's possible to set the coverageThreshold
that will enforce how much of coverage is necessary for the code to pass the tests:
module.exports = {
coverageThreshold: {
global: {
statements: 100,
branches: 100,
functions: 100,
lines: 100,
},
},
};
It's nice to set a bit below what the coverage is as of now, to make sure there won't be much of new code without tests committed.
[!danger] The coverage is not a perfect metric for confidence.
Not all lines in the codebase are equal (some are more important than others).
It's possible to use a glob when setting the coverageThreshold
.
module.exports = {
coverageThreshold: {
"./src/shared/utils.js": {
statements: 100,
branches: 100,
functions: 100,
lines: 100,
},
},
};
Note: When we add the specific files to the configuration, the global
coverage threshold lowers.
The coverage can be added to CI/CD setup using codecov.