乐闻世界logo
搜索文章和话题

How to generate and configure code coverage reports in Jest? What are the coverage metrics?

2月21日 15:54

Jest provides powerful code coverage reporting to help developers understand test coverage:

Generating Coverage Reports:

bash
# Run tests and generate coverage report jest --coverage # Or configure in package.json { "scripts": { "test:coverage": "jest --coverage" } }

Coverage Metrics:

  • Statements: Percentage of executed code statements
  • Branches: Percentage of executed conditional branches
  • Functions: Percentage of called functions
  • Lines: Percentage of executed code lines

Configuring Coverage:

javascript
// jest.config.js module.exports = { collectCoverage: true, collectCoverageFrom: [ 'src/**/*.{js,jsx,ts,tsx}', '!src/**/*.d.ts', '!src/**/*.stories.{js,jsx,ts,tsx}', '!src/index.{js,jsx,ts,tsx}' ], coverageThreshold: { global: { branches: 80, functions: 80, lines: 80, statements: 80 } }, coverageReporters: ['text', 'lcov', 'html'] };

Coverage Report Formats:

  • text: Command line text output
  • lcov: Generates lcov.info file for CI/CD tools
  • html: Generates HTML report for visual inspection
  • json: JSON format report

Best Practices:

  • Set reasonable coverage thresholds (usually 80%)
  • Exclude files that don't need testing (config files, type definitions)
  • Integrate coverage checks in CI/CD
  • Regularly review uncovered code
  • Focus on core business logic coverage
标签:Jest