V8-based code coverage provider for Vitest testing framework with precise coverage collection and reporting capabilities.
npx @tessl/cli install tessl/npm-vitest--coverage-v8@3.2.00
# @vitest/coverage-v8
1
2
@vitest/coverage-v8 is the official V8-based code coverage provider for the Vitest testing framework. It leverages Node.js's built-in V8 coverage capabilities to provide precise, high-performance coverage collection with minimal overhead, supporting both Node.js and browser environments.
3
4
## Package Information
5
6
- **Package Name**: @vitest/coverage-v8
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @vitest/coverage-v8`
10
11
## Core Imports
12
13
```typescript
14
// Main coverage provider module (Node.js)
15
import coverageModule from "@vitest/coverage-v8";
16
17
// Browser coverage provider module
18
import browserCoverageModule from "@vitest/coverage-v8/browser";
19
```
20
21
For CommonJS:
22
23
```javascript
24
const coverageModule = require("@vitest/coverage-v8");
25
const browserCoverageModule = require("@vitest/coverage-v8/browser");
26
```
27
28
## Basic Usage
29
30
The coverage provider is typically used internally by Vitest, but can be configured and used directly:
31
32
```typescript
33
import coverageModule from "@vitest/coverage-v8";
34
import browserCoverageModule from "@vitest/coverage-v8/browser";
35
36
// Using the Node.js coverage module
37
await coverageModule.startCoverage({ isolate: false });
38
const coverage = await coverageModule.takeCoverage();
39
await coverageModule.stopCoverage({ isolate: false });
40
41
// Using the browser coverage module
42
await browserCoverageModule.startCoverage();
43
const browserCoverage = await browserCoverageModule.takeCoverage();
44
// No stopCoverage() call needed in browser mode
45
46
// Using the provider directly
47
const provider = await coverageModule.getProvider();
48
await provider.generateReports(coverageMap);
49
```
50
51
## Architecture
52
53
@vitest/coverage-v8 is built around several key components:
54
55
- **Coverage Module**: Runtime coverage collection interface compatible with Vitest's coverage system
56
- **V8 Provider**: Main coverage provider implementing full coverage generation and reporting
57
- **Browser Support**: Separate browser-optimized implementation using Chrome DevTools Protocol
58
- **Source Map Integration**: Comprehensive source map remapping for accurate coverage of transpiled code
59
- **Istanbul Compatibility**: Converts V8 coverage data to Istanbul format for broad reporting ecosystem support
60
61
## Capabilities
62
63
### Node.js Coverage Collection
64
65
Runtime coverage collection using Node.js Inspector API for precise V8-native coverage data.
66
67
```typescript { .api }
68
interface CoverageProviderModule {
69
/**
70
* Initialize V8 coverage collection with precision settings
71
* @param options - Configuration for coverage isolation
72
*/
73
startCoverage(options: { isolate: boolean }): Promise<void>;
74
75
/**
76
* Collect current coverage data from V8 profiler
77
* @param options - Optional module execution information for offset calculation
78
* @returns Promise resolving to script coverage with offset data
79
*/
80
takeCoverage(options?: {
81
moduleExecutionInfo?: Map<string, { startOffset: number }>;
82
}): Promise<{ result: ScriptCoverageWithOffset[] }>;
83
84
/**
85
* Stop coverage collection and clean up V8 profiler session
86
* @param options - Configuration for coverage isolation
87
*/
88
stopCoverage(options: { isolate: boolean }): Promise<void>;
89
90
/**
91
* Factory method to create a V8CoverageProvider instance
92
* @returns Promise resolving to configured provider
93
*/
94
getProvider(): Promise<V8CoverageProvider>;
95
}
96
```
97
98
### Browser Coverage Collection
99
100
Browser-optimized coverage collection using Chrome DevTools Protocol for web-based testing environments.
101
102
```typescript { .api }
103
interface BrowserCoverageProviderModule {
104
/**
105
* Initialize browser coverage collection using CDP
106
*/
107
startCoverage(): Promise<void>;
108
109
/**
110
* Collect coverage data from browser with automatic filtering
111
* Filters out node_modules, Vitest internal files, and non-origin URLs
112
* @returns Promise resolving to filtered coverage results with decoded URLs
113
*/
114
takeCoverage(): Promise<{ result: ScriptCoverage[] }>;
115
116
/**
117
* No-op in browser mode as coverage session is shared between tests
118
*/
119
stopCoverage(): void;
120
121
/**
122
* Factory method to create a V8CoverageProvider instance
123
* @returns Promise resolving to configured provider
124
*/
125
getProvider(): Promise<V8CoverageProvider>;
126
}
127
```
128
129
### Coverage Provider
130
131
Main coverage provider class implementing full coverage generation, reporting, and source map integration.
132
133
```typescript { .api }
134
class V8CoverageProvider extends BaseCoverageProvider<ResolvedCoverageOptions<'v8'>> {
135
/** Provider identifier */
136
readonly name: 'v8';
137
/** Package version for compatibility checking */
138
version: string;
139
/** File exclusion handler for coverage filtering */
140
testExclude: InstanceType<typeof TestExclude>;
141
142
/**
143
* Initialize provider with Vitest context and configuration
144
* @param ctx - Vitest instance providing configuration and utilities
145
*/
146
initialize(ctx: Vitest): void;
147
148
/**
149
* Create empty Istanbul coverage map for data aggregation
150
* @returns New coverage map instance
151
*/
152
createCoverageMap(): CoverageMap;
153
154
/**
155
* Generate comprehensive coverage data from collected V8 coverage
156
* @param reportContext - Context information for coverage generation
157
* @returns Promise resolving to populated coverage map
158
*/
159
generateCoverage(reportContext: ReportContext): Promise<CoverageMap>;
160
161
/**
162
* Generate coverage reports in multiple formats from coverage map
163
* @param coverageMap - Istanbul coverage map containing coverage data
164
* @param allTestsRun - Optional flag indicating if all tests were executed
165
*/
166
generateReports(coverageMap: CoverageMap, allTestsRun?: boolean): Promise<void>;
167
168
/**
169
* Parse configuration module using magicast for dynamic config handling
170
* @param configFilePath - Path to configuration file to parse
171
* @returns Promise resolving to proxified module for manipulation
172
*/
173
parseConfigModule(configFilePath: string): Promise<ProxifiedModule<any>>;
174
}
175
```
176
177
### Coverage Data Types
178
179
Core data structures used throughout the coverage collection and processing pipeline.
180
181
```typescript { .api }
182
/**
183
* V8 script coverage extended with offset information for accurate source mapping
184
*/
185
interface ScriptCoverageWithOffset extends Profiler.ScriptCoverage {
186
/** Starting offset for coverage measurement within the file */
187
startOffset: number;
188
}
189
190
/**
191
* Context information provided during coverage report generation
192
*/
193
interface ReportContext {
194
/** Indicates whether all tests were run (false for specific test execution) */
195
allTestsRun?: boolean;
196
}
197
198
/**
199
* V8-specific coverage configuration options extending base coverage settings
200
*/
201
interface CoverageV8Options extends BaseCoverageOptions {
202
/** Ignore empty lines, comments and non-runtime code (requires experimentalAstAwareRemapping: false) */
203
ignoreEmptyLines?: boolean;
204
/** Enable experimental AST-based analysis for more accurate results */
205
experimentalAstAwareRemapping?: boolean;
206
/** Array of class method names to ignore for coverage (requires experimentalAstAwareRemapping: true) */
207
ignoreClassMethods?: string[];
208
}
209
```
210
211
## Types
212
213
```typescript { .api }
214
/**
215
* Coverage provider module interface compatible with Vitest's runtime system
216
*/
217
interface CoverageProviderModule {
218
startCoverage(options: { isolate: boolean }): Promise<void>;
219
takeCoverage(options?: { moduleExecutionInfo?: Map<string, { startOffset: number }> }): Promise<{ result: ScriptCoverageWithOffset[] }>;
220
stopCoverage(options: { isolate: boolean }): Promise<void>;
221
getProvider(): Promise<V8CoverageProvider>;
222
}
223
224
/**
225
* Browser-specific coverage provider module with CDP integration
226
*/
227
interface BrowserCoverageProviderModule {
228
startCoverage(): Promise<void>;
229
takeCoverage(): Promise<{ result: ScriptCoverage[] }>;
230
stopCoverage(): void;
231
getProvider(): Promise<V8CoverageProvider>;
232
}
233
234
/**
235
* Main coverage provider class extending Vitest's base provider
236
*/
237
declare class V8CoverageProvider extends BaseCoverageProvider<ResolvedCoverageOptions<'v8'>> {
238
name: 'v8';
239
version: string;
240
testExclude: InstanceType<typeof TestExclude>;
241
initialize(ctx: Vitest): void;
242
createCoverageMap(): CoverageMap;
243
generateCoverage(reportContext: ReportContext): Promise<CoverageMap>;
244
generateReports(coverageMap: CoverageMap, allTestsRun?: boolean): Promise<void>;
245
parseConfigModule(configFilePath: string): Promise<ProxifiedModule<any>>;
246
}
247
248
/**
249
* V8 script coverage with additional offset information for source mapping
250
*/
251
interface ScriptCoverageWithOffset extends Profiler.ScriptCoverage {
252
startOffset: number;
253
}
254
255
/**
256
* Report generation context providing execution metadata
257
*/
258
interface ReportContext {
259
allTestsRun?: boolean;
260
}
261
262
/**
263
* V8-specific coverage configuration options
264
*/
265
interface CoverageV8Options extends BaseCoverageOptions {
266
ignoreEmptyLines?: boolean;
267
experimentalAstAwareRemapping?: boolean;
268
ignoreClassMethods?: string[];
269
}
270
271
/**
272
* Base coverage options shared across all coverage providers
273
*/
274
interface BaseCoverageOptions {
275
enabled?: boolean;
276
include?: string[];
277
exclude?: string[];
278
extension?: string | string[];
279
all?: boolean;
280
clean?: boolean;
281
cleanOnRerun?: boolean;
282
reportsDirectory?: string;
283
reporter?: any[];
284
skipFull?: boolean;
285
thresholds?: any;
286
watermarks?: any;
287
reportOnFailure?: boolean;
288
allowExternal?: boolean;
289
excludeAfterRemap?: boolean;
290
processingConcurrency?: number;
291
}
292
293
/**
294
* Istanbul coverage map for coverage data aggregation
295
*/
296
declare class CoverageMap {
297
merge(coverageMap: CoverageMap): void;
298
filter(predicate: (filename: string) => boolean): void;
299
files(): string[];
300
}
301
302
/**
303
* Script coverage data structure from V8 profiler
304
*/
305
interface ScriptCoverage {
306
/** Script URL */
307
url: string;
308
/** Coverage data for script functions */
309
functions: FunctionCoverage[];
310
}
311
312
/**
313
* Coverage data for individual functions
314
*/
315
interface FunctionCoverage {
316
/** Function name */
317
functionName: string;
318
/** Array of ranges with execution counts */
319
ranges: CoverageRange[];
320
/** Indicates if function is a block-level function */
321
isBlockCoverage: boolean;
322
}
323
324
/**
325
* Coverage range with execution count
326
*/
327
interface CoverageRange {
328
/** Start character offset */
329
startOffset: number;
330
/** End character offset */
331
endOffset: number;
332
/** Number of times this range was executed */
333
count: number;
334
}
335
336
/**
337
* Node.js V8 profiler script coverage interface
338
*/
339
interface Profiler {
340
ScriptCoverage: ScriptCoverage;
341
}
342
343
/**
344
* Magicast proxified module for dynamic code manipulation
345
*/
346
interface ProxifiedModule<T> {
347
generate(): { code: string };
348
}
349
350
/**
351
* Test exclusion utility for filtering files
352
*/
353
declare class TestExclude {
354
constructor(options: any);
355
shouldInstrument(filename: string): boolean;
356
glob(root: string): Promise<string[]>;
357
}
358
359
/**
360
* Vitest core instance providing configuration and utilities
361
*/
362
interface Vitest {
363
config: {
364
root: string;
365
coverage: any;
366
};
367
logger: {
368
log(message: string): void;
369
error(message: string, error?: any): void;
370
warn(message: string): void;
371
};
372
version: string;
373
}
374
375
/**
376
* Base coverage provider class from Vitest
377
*/
378
declare class BaseCoverageProvider<T> {
379
options: T;
380
ctx: Vitest;
381
_initialize(ctx: Vitest): void;
382
hasTerminalReporter(reporters: any[]): boolean;
383
toSlices<U>(items: U[], concurrency: number): U[][];
384
createUncoveredFileTransformer(ctx: Vitest): any;
385
readCoverageFiles<U>(options: {
386
onFileRead: (coverage: U) => void;
387
onFinished: (project: any, transformMode?: string) => Promise<void>;
388
onDebug: (message: string) => void;
389
}): Promise<void>;
390
reportThresholds(coverageMap: CoverageMap, allTestsRun?: boolean): Promise<void>;
391
}
392
393
/**
394
* Resolved coverage options with all defaults applied
395
*/
396
type ResolvedCoverageOptions<T> = T extends 'v8' ? CoverageV8Options & {
397
enabled: boolean;
398
clean: boolean;
399
cleanOnRerun: boolean;
400
reportsDirectory: string;
401
exclude: string[];
402
extension: string[];
403
reportOnFailure: boolean;
404
allowExternal: boolean;
405
processingConcurrency: number;
406
reporter: any[];
407
} : any;
408
```