V8 Coverage with Vitest: Native Coverage Without Instrumentation
Vitest ships with two coverage providers: Istanbul (the classic instrumentation approach) and V8 (native runtime coverage). Understanding the difference matters more than most teams realize — they produce different numbers for the same code, and V8's approach is fundamentally more accurate for modern JavaScript patterns. This guide covers when to use each, how to configure V8 coverage, and how to make coverage gates work in CI.
V8 vs Istanbul: What's Actually Different
Istanbul instruments your source code before it runs. It rewrites each file, inserting counter variables at every statement, branch, and function entry point. When your tests execute the instrumented code, those counters increment. Coverage numbers come from those counters.
V8 takes a different approach entirely. Node.js (and Chrome) have a built-in coverage mechanism in the V8 JavaScript engine. V8 records which byte ranges of the compiled JavaScript actually executed. Vitest's V8 provider collects this data directly from the runtime — no source code rewriting required.
The practical differences:
Source maps and transpilation: Istanbul instruments the pre-transpilation source (TypeScript, JSX), so its numbers reflect your original code. V8 instruments the compiled output and uses source maps to map back to originals. For most projects this works correctly, but complex source map scenarios (multi-level transpilation, decorators with unusual transforms) can produce slight discrepancies.
Performance: V8 coverage adds minimal overhead — the engine is already tracking execution. Istanbul's instrumentation adds overhead proportional to code size, typically 10-20% slower test runs.
Branch coverage accuracy: This is where V8 often wins. Consider optional chaining (user?.profile?.name) — Istanbul may not count this as a branch at all, while V8 tracks the actual conditional jumps in the compiled code. For modern TypeScript that uses optional chaining, nullish coalescing, and similar operators heavily, V8 branch coverage is more meaningful.
Setting Up Vitest with V8 Coverage
Install the V8 coverage provider:
npm install --save-dev @vitest/coverage-v8Configure it in vitest.config.ts:
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'lcov', 'html', 'json-summary'],
reportsDirectory: './coverage',
all: true,
include: ['src/**/*.{ts,tsx}'],
exclude: [
'src/**/*.d.ts',
'src/**/*.test.{ts,tsx}',
'src/**/*.spec.{ts,tsx}',
'src/**/*.stories.{ts,tsx}',
'src/generated/**',
'src/main.tsx',
'src/vite-env.d.ts',
],
thresholds: {
lines: 80,
functions: 80,
branches: 75,
statements: 80,
},
},
},
});Run coverage:
npx vitest run --coverageOr add it to your scripts:
{
"scripts": {
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"test:watch": "vitest"
}
}Switching Between Providers
If you're migrating from Istanbul, install the Istanbul provider alongside V8 to compare numbers:
npm install --save-dev @vitest/coverage-istanbulSwitch providers in config:
// Use istanbul
provider: 'istanbul',
// Use v8
provider: 'v8',Run both and compare the output. If you see significantly different branch coverage numbers, V8 is likely detecting branches that Istanbul was ignoring (or vice versa — Istanbul sometimes over-counts branches on certain TypeScript patterns).
For TypeScript projects targeting modern Node.js, V8 is usually the better choice. For projects with complex build pipelines or Babel transforms, Istanbul's source-level instrumentation may be more reliable.
Configuring Thresholds
Vitest's threshold configuration is straightforward but has some nuances worth knowing.
Global thresholds apply across all covered files combined:
thresholds: {
lines: 80,
functions: 85,
branches: 75,
statements: 80,
},Per-file thresholds fail if any individual file falls below the threshold:
thresholds: {
lines: 80,
perFile: true, // Apply thresholds to each file individually
},Per-file thresholds are strict — a single utility file with 60% coverage will fail the entire coverage check. Use them for critical modules rather than globally.
100% thresholds for critical paths — you can set specific files to 100%:
thresholds: {
lines: 80,
branches: 75,
// Individual file overrides via include patterns
},Note that Vitest doesn't currently support per-path threshold overrides in the same way Jest does. For 100% coverage requirements on specific modules, the recommended pattern is to write exhaustive tests and verify manually via the HTML report, or use a separate coverage job for those critical paths.
Exclusion Patterns
The exclude array uses glob patterns matched against file paths relative to the project root. Some patterns that cover common exclusion needs:
exclude: [
// Test files themselves
'src/**/*.{test,spec}.{ts,tsx,js,jsx}',
// Type declarations
'**/*.d.ts',
// Storybook
'**/*.stories.{ts,tsx}',
// Build artifacts
'dist/**',
'build/**',
// Generated code
'src/generated/**',
'**/graphql/**/__generated__/**',
// Entry points with minimal logic
'src/main.{ts,tsx}',
'src/index.{ts,tsx}',
// Configuration files
'vite.config.ts',
'vitest.config.ts',
// Third-party type shims
'src/vite-env.d.ts',
],For line-level exclusions, V8 coverage supports the same Istanbul hint comments:
/* v8 ignore next */
const debugHelper = () => {
console.log('debug only');
};
/* v8 ignore next 3 */
if (process.env.DEBUG_MODE) {
attachDebugHandlers();
}Note the comment format — v8 ignore rather than istanbul ignore. If you're migrating from Istanbul, you'll need to update these comments. Some teams use both forms during transition.
CI Integration and Badge Generation
A typical GitHub Actions setup:
# .github/workflows/coverage.yml
name: Coverage
on:
push:
branches: [main]
pull_request:
jobs:
coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- name: Run tests with coverage
run: npm run test:coverage
- name: Upload coverage reports
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./coverage/lcov.info
fail_ci_if_error: true
- name: Upload HTML report as artifact
uses: actions/upload-artifact@v4
if: always()
with:
name: coverage-html
path: coverage/
retention-days: 14Generating a coverage badge from the json-summary reporter output:
// scripts/generate-badge.ts
import { readFileSync, writeFileSync } from 'fs';
const summary = JSON.parse(readFileSync('coverage/coverage-summary.json', 'utf-8'));
const pct = summary.total.lines.pct;
const color = pct >= 80 ? 'brightgreen' : pct >= 60 ? 'yellow' : 'red';
const badge = {
schemaVersion: 1,
label: 'coverage',
message: `${pct.toFixed(1)}%`,
color,
};
writeFileSync('coverage/badge.json', JSON.stringify(badge, null, 2));
console.log(`Coverage: ${pct.toFixed(1)}% (${color})`);Use Shields.io dynamic badges pointing to your badge.json hosted on GitHub Pages or an artifact store.
Watch Mode and Coverage
One Vitest advantage over Jest is that coverage works well in watch mode for targeted files:
# Run coverage only for changed files in watch mode
vitest --coverage --changed
# Run coverage for a specific directory
vitest run --coverage src/auth/The --changed flag uses git to detect modified files and only runs tests related to them. For large codebases this dramatically speeds up the development loop while still giving you accurate coverage numbers for the code you're actively working on.
V8 coverage with Vitest represents the current state of the art for JavaScript coverage tooling — it's faster than Istanbul, more accurate for modern language features, and integrates cleanly with the Vite ecosystem that most new TypeScript projects use.