0
# Node-Side Runner APIs
1
2
Programmatic APIs for running Vitest from Node.js, useful for custom test runners and integrations. Import from `vitest/node`.
3
4
## Capabilities
5
6
### Creating Vitest Instance
7
8
```typescript { .api }
9
/**
10
* Create a Vitest instance
11
* @param mode - Run mode ('test' or 'benchmark')
12
* @param options - User configuration
13
* @param viteOverrides - Vite-specific overrides
14
* @param vitestOptions - Additional Vitest options
15
* @returns Promise resolving to Vitest instance
16
*/
17
function createVitest(
18
mode: 'test' | 'benchmark',
19
options: UserConfig,
20
viteOverrides?: ViteUserConfig,
21
vitestOptions?: VitestOptions
22
): Promise<Vitest>;
23
24
/**
25
* Start Vitest from CLI
26
* @param cliFilters - Test file filters from CLI
27
* @param options - CLI options
28
* @param viteOverrides - Vite overrides
29
* @returns Promise resolving to Vitest instance or undefined
30
*/
31
function startVitest(
32
cliFilters: string[],
33
options: CliOptions,
34
viteOverrides?: ViteUserConfig
35
): Promise<Vitest | undefined>;
36
```
37
38
**Usage:**
39
40
```typescript
41
import { createVitest } from 'vitest/node';
42
43
const vitest = await createVitest('test', {
44
watch: false,
45
globals: true
46
});
47
48
await vitest.start();
49
await vitest.close();
50
```
51
52
### Vitest Class
53
54
Main test runner class.
55
56
```typescript { .api }
57
class Vitest {
58
/** Vitest version */
59
static version: string;
60
61
/** Start test execution */
62
start(filters?: string[]): Promise<void>;
63
64
/** Close Vitest and cleanup */
65
close(): Promise<void>;
66
67
/** Re-run tests */
68
rerun(files?: string[]): Promise<void>;
69
70
/** Get test results */
71
getTestResults(): Promise<TestResult[]>;
72
73
/** Configuration */
74
config: ResolvedConfig;
75
76
/** Test projects */
77
projects: TestProject[];
78
}
79
```
80
81
### Reporter Classes
82
83
Built-in reporters for test output formatting.
84
85
```typescript { .api }
86
/**
87
* Base reporter class
88
*/
89
abstract class BaseReporter {
90
onInit(ctx: Vitest): void;
91
onPathsCollected(paths?: string[]): void;
92
onCollected(files?: File[]): Promise<void> | void;
93
onFinished(files?: File[], errors?: unknown[]): Promise<void> | void;
94
onTaskUpdate(task: [string, TaskResult | undefined][]): void;
95
onTestRemoved(trigger?: string): void;
96
onWatcherStart(files?: File[], errors?: unknown[]): void;
97
onWatcherRerun(files: string[], trigger?: string): void;
98
onServerRestart(reason?: string): void;
99
onProcessTimeout(): void;
100
}
101
102
/**
103
* Default colored console reporter
104
*/
105
class DefaultReporter extends BaseReporter {}
106
107
/**
108
* Verbose reporter with detailed output
109
*/
110
class VerboseReporter extends BaseReporter {}
111
112
/**
113
* Minimal dot reporter (. = pass, x = fail)
114
*/
115
class DotReporter extends BaseReporter {}
116
117
/**
118
* Tree-structured output
119
*/
120
class TreeReporter extends BaseReporter {}
121
122
/**
123
* JSON output reporter
124
*/
125
class JsonReporter extends BaseReporter {}
126
127
/**
128
* Binary blob reporter for test results
129
*/
130
class BlobReporter extends BaseReporter {}
131
132
/**
133
* TAP (Test Anything Protocol) reporter
134
*/
135
class TapReporter extends BaseReporter {}
136
137
/**
138
* Flat TAP reporter
139
*/
140
class TapFlatReporter extends BaseReporter {}
141
142
/**
143
* JUnit XML reporter
144
*/
145
class JUnitReporter extends BaseReporter {}
146
147
/**
148
* GitHub Actions reporter
149
*/
150
class GithubActionsReporter extends BaseReporter {}
151
152
/**
153
* Hanging process detector
154
*/
155
class HangingProcessReporter extends BaseReporter {}
156
```
157
158
**Usage:**
159
160
```typescript
161
import { createVitest, DefaultReporter, JsonReporter } from 'vitest/node';
162
163
const vitest = await createVitest('test', {
164
reporters: [new DefaultReporter(), new JsonReporter()]
165
});
166
```
167
168
### Test Sequencers
169
170
Control test execution order.
171
172
```typescript { .api }
173
/**
174
* Base sequencer class
175
*/
176
abstract class BaseSequencer {
177
abstract sort(files: File[]): Promise<File[]>;
178
abstract shard(files: File[]): Promise<File[]>;
179
}
180
181
/**
182
* Random test sequencer
183
*/
184
class RandomSequencer extends BaseSequencer {
185
sort(files: File[]): Promise<File[]>;
186
shard(files: File[]): Promise<File[]>;
187
}
188
```
189
190
**Usage:**
191
192
```typescript
193
import { defineConfig } from 'vitest/config';
194
import { RandomSequencer } from 'vitest/node';
195
196
export default defineConfig({
197
test: {
198
sequence: {
199
sequencer: RandomSequencer
200
}
201
}
202
});
203
```
204
205
### Test Collection Classes
206
207
```typescript { .api }
208
class TestProject {
209
name: string;
210
config: ResolvedConfig;
211
212
globTestFiles(filters?: string[]): Promise<string[]>;
213
isTestFile(file: string): boolean;
214
}
215
216
class TestModule {
217
id: string;
218
filepath: string;
219
tasks: (TestCase | TestSuite)[];
220
}
221
222
class TestSuite {
223
id: string;
224
name: string;
225
tasks: (TestCase | TestSuite)[];
226
}
227
228
class TestCase {
229
id: string;
230
name: string;
231
result?: TestResult;
232
}
233
```
234
235
### Configuration Resolution
236
237
```typescript { .api }
238
/**
239
* Resolve Vitest configuration
240
* @param config - User configuration
241
* @param mode - Run mode
242
* @returns Promise resolving to resolved configuration
243
*/
244
function resolveConfig(
245
config?: UserConfig,
246
mode?: 'test' | 'benchmark'
247
): Promise<ResolvedConfig>;
248
```
249
250
### CLI Parsing
251
252
```typescript { .api }
253
/**
254
* Parse CLI arguments
255
* @param args - Command line arguments
256
* @param options - Parse options
257
* @returns Parsed options and filters
258
*/
259
function parseCLI(
260
args: string[],
261
options?: CliParseOptions
262
): { options: CliOptions; filters: string[] };
263
```
264
265
## Common Use Cases
266
267
### Custom Test Runner
268
269
```typescript
270
import { createVitest, DefaultReporter } from 'vitest/node';
271
272
async function runTests() {
273
const vitest = await createVitest('test', {
274
watch: false,
275
reporters: [new DefaultReporter()]
276
});
277
278
await vitest.start(['**/*.test.ts']);
279
280
const results = await vitest.getTestResults();
281
const failed = results.some(r => r.state === 'fail');
282
283
await vitest.close();
284
285
process.exit(failed ? 1 : 0);
286
}
287
288
runTests();
289
```
290
291
### Custom Reporter
292
293
```typescript
294
import { BaseReporter } from 'vitest/node';
295
import type { File } from 'vitest';
296
297
class CustomReporter extends BaseReporter {
298
onCollected(files?: File[]) {
299
console.log(`Collected ${files?.length} test files`);
300
}
301
302
onFinished(files?: File[], errors?: unknown[]) {
303
const total = files?.reduce((acc, file) => {
304
return acc + file.tasks.length;
305
}, 0) || 0;
306
307
console.log(`Total tests: ${total}`);
308
309
if (errors?.length) {
310
console.error(`Errors: ${errors.length}`);
311
}
312
}
313
}
314
315
// Use in config
316
export default defineConfig({
317
test: {
318
reporters: [new CustomReporter()]
319
}
320
});
321
```
322
323
### Programmatic Test Execution with Filtering
324
325
```typescript
326
import { createVitest } from 'vitest/node';
327
328
async function runSpecificTests() {
329
const vitest = await createVitest('test', {});
330
331
// Run only tests matching pattern
332
await vitest.start(['src/utils/*.test.ts']);
333
334
// Or rerun specific files
335
await vitest.rerun(['src/utils/math.test.ts']);
336
337
await vitest.close();
338
}
339
```
340
341
## Type Definitions
342
343
```typescript { .api }
344
interface Vitest {
345
version: string;
346
config: ResolvedConfig;
347
projects: TestProject[];
348
start(filters?: string[]): Promise<void>;
349
close(): Promise<void>;
350
rerun(files?: string[]): Promise<void>;
351
getTestResults(): Promise<TestResult[]>;
352
}
353
354
interface VitestOptions {
355
stdin?: NodeJS.ReadStream;
356
stdout?: NodeJS.WriteStream;
357
stderr?: NodeJS.WriteStream;
358
}
359
360
interface CliOptions extends UserConfig {
361
run?: boolean;
362
watch?: boolean;
363
reporter?: string[];
364
outputFile?: string;
365
}
366
367
type TestResult = TestResultPassed | TestResultFailed | TestResultSkipped;
368
369
interface TestResultPassed {
370
state: 'pass';
371
duration: number;
372
}
373
374
interface TestResultFailed {
375
state: 'fail';
376
error: Error;
377
duration: number;
378
}
379
380
interface TestResultSkipped {
381
state: 'skip';
382
}
383
```
384