How to get the code coverage report using Jest?
In order to generate a code coverage report using Jest, you use the --coverage
flag:
Jest strategically gathers coverage data and deposits a complete report in the coverage/
directory. The detailed report can be accessed through coverage/lcov-report/index.html
in your preferred web browser.
If you're using Jest prior to version 21.2.1, consider upgrading to take advantage of expanded coverage features. If you're using npm
or yarn
, your package.json
script can be configured as such:
You can then execute the coverage report with npm test -- --coverage
or yarn test --coverage
. Modify the collectCoverage
and coverageReporters
settings within Jest's config for tailored coverage collection.
Expanding your code coverage reports
Upgrade Jest to latest version
The first step is to upgrade Jest. Ensure you're using Jest 23.6 or later to fully utilize code coverage features.
Configuring Jest
Configure jest.config.js
as follows:
Using npx for testing locally
If Jest isn't installed globally, run tests with npx:
Understanding report formats
Jest offers a variety of coverage report formats:
json
: Perfect for machine processing.html
: The lcov HTML report is a visual gold mine.text
: Provides a quick and easy CLI overview.
Identifying problem areas
Pull back the curtain on infamous problem areas. Use coverage data to direct your testing focus toward under-tested areas and improve your suite's robustness.
Deep dive into Jest
You can command Jest to generate coverage for specific test files with npx jest --coverage
. Also, consider integrating Istanbul with Jest for more robust coverage options.
Code coverage tools in CI
Use CI services like Codecov or Coveralls. Upload your json
coverage report for continuous monitoring and trends overview. This promotes high code quality in team projects.
Enforce coverage thresholds
Set coverage percentage enforcement in your jest.config.js
:
This feature ensures that failing coverage doesn't slip through CI unnoticed.
Beware False Positives
Whilst high coverage percentage is desirable, it's not definitive proof of a quality test suite. High score without quality assertions is just painting the numbers without appreciating the art. (Reddit joke #2)
Was this article helpful?