Code Coverage — Explained with Examples
Code coverage measures how much of your source code is executed during testing, helping identify untested paths and improve test quality.
Code coverage is a metric. It tells you what code ran during tests, not whether the code is correct or the tests are meaningful. High coverage doesn’t mean bug-free code, but low coverage means large untested areas.
Types of Coverage
Line coverage — percentage of executable lines executed during tests.
Branch coverage — percentage of decision points (if/else, switch cases) where both true and false branches were taken.
Function coverage — percentage of functions or methods called.
Statement coverage — percentage of statements executed.
function calculateDiscount(price, isMember) {
let discount = 0; // Line 1
if (isMember) { // Branch 1 (true/false)
discount = price * 0.1; // Line 3
}
if (price > 100) { // Branch 2 (true/false)
discount += price * 0.05; // Line 6
}
return price - discount; // Line 8
}
// Test that only hits true branch of isMember
test('member discount', () => {
expect(calculateDiscount(200, true)).toBe(170);
// Line coverage: 1,3,6,8 = 100%
// Branch coverage: isMember=true=yes, isMember=false=no → 50%
// price>100=true=yes, price>100=false=no → 50%
});Running Coverage with Jest
npx jest --coverage-----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------|---------|----------|---------|---------|-------------------
All files | 87.5 | 75 | 100 | 87.5 |
discount.js | 87.5 | 75 | 100 | 87.5 | 5-6
-----------------|---------|----------|---------|---------|-------------------Real-World Analogy
Code coverage is like a GPS tracking system for a delivery truck. It shows which streets (code paths) the truck drove on during its route (test run). If the truck never went down Maple Street, you know that area wasn’t serviced. But seeing the truck on Maple Street doesn’t tell you whether packages were actually delivered there (code coverage doesn’t verify correctness).
Coverage Traps
High coverage (90%+) can create false confidence. Common pitfalls:
- Testing trivial getters/setters to inflate numbers
- Writing tests that assert nothing meaningful
- Missing edge cases that are covered by line count but not logic
Related Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro