Sub topic 15
Measuring Code Coverage
Code coverage tells you which parts of your source code ran while your tests ran. It does not tell you whether those parts work. Coverage is good at finding code that no test touches. It is a poor measure of test quality. This chapter covers how Vitest collects coverage, how to read the reports, how to enforce minimums with thresholds, and where coverage numbers mislead you.
This chapter assumes you can write and run Vitest tests, use expect matchers, and edit a vitest.config.js file, as covered in the earlier chapters on setup, assertions, and configuration.
How Vitest Collects Coverage
Vitest does not measure coverage itself. It hands the job to a coverage provider, a separate package that you install next to Vitest. There are two official providers:
@vitest/coverage-v8uses the coverage data that the V8 JavaScript engine (the engine inside Node.js) already records while it runs code. This is the default provider.@vitest/coverage-istanbulrewrites your source code before it runs, inserting counters into every statement, branch, and function. This technique is called instrumentation.
Both providers produce the same kinds of reports, so the rest of your workflow does not change when you switch between them.
Choosing a provider
| Concern | v8 | istanbul |
|---|---|---|
| Setup | Default, nothing extra to configure | Set `provider: 'istanbul'` |
| Speed | Usually faster, no source rewriting | Slower, every file is transformed |
| Runtime support | Needs a V8-based runtime (Node.js, Chromium) | Works in any JavaScript runtime |
| Ignore comments | `/* v8 ignore next */` | `/* istanbul ignore next */` |
| Typical choice | Most Node.js projects | Non-V8 runtimes, or when matching an existing Istanbul setup |
Start with v8 unless you have a specific reason not to.
Installing and Running Coverage
Install the provider as a dev dependency:
npm install --save-dev @vitest/coverage-v8Then run your tests with the --coverage flag:
npx vitest run --coveragevitest run gives a single run, which is what you want in CI. Coverage also works in watch mode with npx vitest --coverage, but rerunning coverage on every save is slower and rarely useful.
Add a script so the whole team uses the same command:
{
"scripts": {
"test": "vitest",
"coverage": "vitest run --coverage"
}
}By default, reports go into a coverage/ folder in the project root. Add it to .gitignore, because it is generated output:
echo "coverage/" >> .gitignoreA Worked Example
Here is a small module with several branches:
// src/shipping.js
export function shippingCost(total, country) {
if (total >= 100) {
return 0
}
if (country === 'US') {
return 5
}
return 15
}
export function formatPrice(amount) {
return `$${amount.toFixed(2)}`
}And a test file that covers only part of it:
// src/shipping.test.js
import { describe, it, expect } from 'vitest'
import { shippingCost } from './shipping.js'
describe('shippingCost', () => {
it('is free for orders of 100 or more', () => {
expect(shippingCost(150, 'US')).toBe(0)
})
it('costs 5 inside the US', () => {
expect(shippingCost(20, 'US')).toBe(5)
})
})Run npx vitest run --coverage. The text reporter prints a table in the terminal with one row per file. For shipping.js, the % Funcs column is below 100 because formatPrice never ran. % Branch is below 100 because the country === 'US' check never took its false path. The Uncovered Line #s column lists the line numbers of return 15 and the body of formatPrice. Those line numbers tell you which tests are missing.
The four metrics
| Metric | What counts as covered | Column | Column |
|---|---|---|---|
| Statements (`% Stmts`) | Each executable statement that ran at least once | ||
| Branches (`% Branch`) | Each path of every `if`, `else`, ternary, `switch` case, `&&`, `\ | \ | `, `??`, and default parameter |
| Functions (`% Funcs`) | Each function that was called at least once | ||
| Lines (`% Lines`) | Each source line containing code that ran |
Branch coverage is the most informative of the four. A line can show as covered while one side of a condition on that line never ran. In const name = user.nickname ?? user.first, the line is covered as soon as it runs, but the branch after ?? is covered only when nickname is null or undefined.
To reach full coverage of shipping.js, add these tests:
import { it, expect } from 'vitest'
import { shippingCost, formatPrice } from './shipping.js'
it('costs 15 outside the US', () => {
expect(shippingCost(20, 'FR')).toBe(15)
})
it('formats a price with two decimals', () => {
expect(formatPrice(5)).toBe('$5.00')
})Reading the HTML Report
The terminal table is fine for a quick check. For finding gaps, the HTML report is better. Configure it in vitest.config.js:
// vitest.config.js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
reportsDirectory: './coverage',
include: ['src/**/*.js'],
exclude: ['src/**/*.test.js'],
},
},
})After a coverage run, open coverage/index.html in a browser. Each file page shows your source with colored highlighting:
- Red lines never ran.
- Yellow highlights mark branches that were not taken.
- A number in the left margin shows how many times each line ran.
- An
IorEmarker means theiforelsepath of that statement was never taken.
The lcov reporter writes coverage/lcov.info, the format most CI services and editor plugins read. Add json-summary if a script needs the totals in a machine-readable form.
Include, Exclude, and Untested Files
There is an easy mistake here. If a file is never imported by any test, the provider never sees it. Without an include pattern, that file can drop out of the report entirely, and your percentages look better than they really are.
Setting include to your source folder makes Vitest report every matching file, including files with 0% coverage. This is the single most useful coverage setting. Use exclude for files that should not count, such as test files, generated code, type declarations, or configuration files.
When a single line truly cannot be tested, such as a defensive check for an impossible state, you can ignore it with a comment that matches your provider:
export function assertNever(value) {
/* v8 ignore next */
throw new Error(`Unexpected value: ${value}`)
}For longer regions, use /* v8 ignore start */ and /* v8 ignore stop */.
Enforcing Minimums with Thresholds
Thresholds make the coverage run fail when coverage drops below a minimum. This stops coverage from quietly shrinking over time:
// vitest.config.js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
coverage: {
provider: 'v8',
include: ['src/**/*.js'],
thresholds: {
lines: 80,
functions: 80,
branches: 75,
statements: 80,
},
},
},
})When a threshold is missed, Vitest prints an error naming the metric, the actual value, and the required value, and exits with code 1. CI treats that as a failure. Other useful options:
thresholds.perFile: trueapplies the limits to every file rather than to the project total. This stops one well-tested file from hiding an untested one.thresholds.autoUpdate: trueraises the numbers in your config when coverage goes up, so the bar only ever rises. Review those config changes in code review like any other change.
What Coverage Does Not Tell You
Coverage records that code ran. It does not record whether anything was checked. This test gives shippingCost 100% coverage and verifies nothing:
import { it } from 'vitest'
import { shippingCost } from './shipping.js'
it('runs every branch', () => {
shippingCost(150, 'US')
shippingCost(20, 'US')
shippingCost(20, 'FR')
})Other common ways coverage misleads:
- Mocked modules. When
vi.mockreplaces a module, the real module's code never runs, so it shows as uncovered even if other tests exercise it indirectly. - Missing inputs. Every branch can be covered while edge cases like
0, negative numbers,NaN, or empty strings are never tried. - Chasing 100%. Pushing for the last few percent tends to produce brittle tests of trivial code. A steady 80–90% with meaningful assertions is a common, practical target.
Use coverage to ask "which behavior has no test at all?" Then write tests that assert on that behavior.
Exercises
Exercise
Your project has src/report.js, but no test imports it, and the coverage table does not list it at all. Which setting fixes this, and why does the file go missing?
Show answer
Set coverage.include to a pattern such as ['src/**/*.js']. The provider only sees files that are loaded during the test run. With an include pattern, Vitest also reports matching files that were never loaded, showing them at 0% so they count against the totals and thresholds.
Exercise
A function discount(price, code) contains const rate = code === 'VIP' ? 0.2 : 0. Your only test calls discount(100, 'VIP'). Which coverage metric shows the gap, and what test closes it?
Show answer
Branch coverage. Line and statement coverage count the ternary line as covered because it ran, but the false path (0) was never taken. Add a test such as expect(discount(100, 'NONE')).toBe(100), assuming the function returns the price minus the discount.
Exercise
You want CI to fail if any single file drops below 70% branch coverage, even when the project total is higher. Write the coverage config block.
Show answer
coverage: { provider: 'v8', include: ['src/*/.js'], thresholds: { branches: 70, perFile: true } }. Then run it in CI with npx vitest run --coverage so the thresholds are actually checked.