Coverage Analysis and Gap Filling
What you'll build
A utility module with conditional branches, analyzed with Jest coverage to find untested paths, then improved with targeted tests that cover the gaps.
Goals
- Generate and read coverage reports
- Identify uncovered branches and lines
- Write meaningful tests for coverage gaps (not just coverage-chasing)
- Understand branch vs line vs function coverage
- Configure coverage thresholds
Prerequisites
- Completed Project 1 or equivalent Jest experience
- Understanding of if/else and switch statements
Steps
- 1
Create a module with branches
Create
gradeUtils.jswith a function that has multiple branches.Codefunction getGrade(score) { if (score < 0 || score > 100) return 'Invalid'; if (score >= 90) return 'A'; if (score >= 80) return 'B'; if (score >= 70) return 'C'; if (score >= 60) return 'D'; return 'F'; } module.exports = { getGrade };Expected result
gradeUtils.js is created.
- 2
Write initial tests (with gaps)
Write tests for only some grades, intentionally leaving gaps.
Codeconst { getGrade } = require('./gradeUtils'); test('returns A for 95', () => { expect(getGrade(95)).toBe('A'); }); test('returns F for 50', () => { expect(getGrade(50)).toBe('F'); });Expected result
Tests pass but coverage is incomplete.
- 3
Generate coverage report
Run
npx jest --coverageand examine the report.Expected result
Coverage report shows uncovered branches (B, C, D, Invalid).
- 4
Fill coverage gaps with meaningful tests
Add tests for each uncovered branch. Make sure each test has a meaningful assertion.
Codetest('returns B for 85', () => { expect(getGrade(85)).toBe('B'); }); test('returns C for 75', () => { expect(getGrade(75)).toBe('C'); }); test('returns D for 65', () => { expect(getGrade(65)).toBe('D'); }); test('returns Invalid for negative', () => { expect(getGrade(-1)).toBe('Invalid'); }); test('returns Invalid for over 100', () => { expect(getGrade(101)).toBe('Invalid'); });Expected result
Coverage is now 100% with meaningful tests.
- 5
Set coverage thresholds
Configure Jest to enforce minimum coverage in package.json.
Code"jest": { "coverageThreshold": { "global": { "branches": 100, "functions": 100, "lines": 100, "statements": 100 } } }Expected result
Tests fail if coverage drops below 100%.
Try it yourself
What you learned
You learned to generate and interpret coverage reports, identify uncovered branches, and fill gaps with meaningful tests. You also learned to set coverage thresholds to prevent coverage from degrading over time. Remember: coverage measures execution, not correctness.
Related Resources
Related Lessons
- Test Coverage
Measuring and interpreting coverage.
- Code Coverage
Coverage metrics explained.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.