Coverage
- Node.js course
- Advanced
- Lesson 76/83
- 5 min
Learn test coverage measurement.
Coverage
Coverage shows what percentage of your code is tested. High coverage means your tests exercise most of the code. Jest offers a built-in coverage tool: jest --coverage.
Example: running jest --coverage shows for each file how many lines, functions and branches are tested. The coverage report highlights untested code. High coverage is a good start, but it does not guarantee quality. What matters is testing critical paths. If coverage is low, important branches are usually untested. Adding tests and raising coverage improves code reliability. Production systems aim for 80%+ coverage.
Coverage types
Coverage has three main types: lines, functions, and branches. Line coverage shows how many lines ran, function coverage how many functions were called, branch coverage how many sides of if-else branches were tested.
Example: for an if (x > 0) branch, both x > 0 and x <= 0 cases must be tested. If only one is tested, line coverage can be 100% but branch coverage is 50%. Branch coverage is the hardest and most valuable; it guarantees critical paths are tested. The coverage report shows which lines and branches were not tested. This tells you where to add tests.
Practice Calculate coverage
Define a calcCoverage(total, tested) function. Return the percentage with return (tested / total) * 100. Print calcCoverage(100, 80) with console.log.
Starter code
// Define the calcCoverage function
// write here
// Print the result
// write hereSample solution
function calcCoverage(total, tested) {
return (tested / total) * 100;
}
console.log(calcCoverage(100, 80));Expected output
80
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does coverage measure?
jest --coverage- Memory usage
- Disk fill rate
- What percentage of code is tested Correct answer
- The app's speed
Explanation: Coverage measures test coverage.
2 Complete the coverage command
jest --____
jest --coverage
Explanation: jest --coverage produces a coverage report.
3 Match each type to its meaning
| Term | Meaning |
|---|---|
lines |
Lines that ran |
functions |
Functions called |
branches |
If-else sides tested |
--coverage |
Jest flag |