Explain Codes LogoExplain Codes Logo

How to get the code coverage report using Jest?

javascript
test-engineering
best-practices
code-coverage
Anton ShumikhinbyAnton Shumikhin·Oct 7, 2024
TLDR

In order to generate a code coverage report using Jest, you use the --coverage flag:

jest --coverage

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:

"scripts": { "test": "jest", "test:coverage": "jest --coverage" }

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:

module.exports = { collectCoverage: true, coverageReporters: ['json', 'lcov', 'text', 'clover'] };

Using npx for testing locally

If Jest isn't installed globally, run tests with npx:

npx jest --coverage // "npx" - the unsung hero in the JavaScript world (Reddit joke #1)

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:

module.exports = { // ... coverageThreshold: { global: { statements: 80, branches: 80, functions: 80, lines: 80 } } };

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)