vitest 3.0.7 → 3.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/browser.d.ts +14 -43
  2. package/dist/browser.js +4 -4
  3. package/dist/chunks/{base.BgUWWWYp.js → base.DV59CbtV.js} +2 -2
  4. package/dist/chunks/{benchmark.Cdu9hjj4.js → benchmark.DL72EVN-.js} +1 -1
  5. package/dist/chunks/{benchmark.CFFwLv-O.d.ts → benchmark.d.BwvBVTda.d.ts} +11 -11
  6. package/dist/chunks/{cac.87F_onld.js → cac.CeVHgzve.js} +30 -6
  7. package/dist/chunks/{cli-api.BZbq1zTX.js → cli-api.Ckwz_xSb.js} +21 -23
  8. package/dist/chunks/config.d.DevWltVl.d.ts +218 -0
  9. package/dist/chunks/{constants.fzPh7AOq.js → constants.DTYd6dNH.js} +1 -1
  10. package/dist/chunks/{coverage.DnNIv-kJ.js → coverage.A3sS5-Wm.js} +1 -29
  11. package/dist/chunks/coverage.d.S9RMNXIe.d.ts +35 -0
  12. package/dist/chunks/{resolveConfig.BbcK25zb.js → coverage.gV8doR2Y.js} +500 -131
  13. package/dist/chunks/{creator.2CFRE1Yx.js → creator.BsBnpTzI.js} +1 -1
  14. package/dist/chunks/defaults.C2Ndd9wx.js +119 -0
  15. package/dist/chunks/env.D4Lgay0q.js +8 -0
  16. package/dist/chunks/environment.d.C8UItCbf.d.ts +170 -0
  17. package/dist/chunks/{execute.Bhwls1-Z.js → execute.eDH0aFFd.js} +4 -4
  18. package/dist/chunks/global.d.Cg2sEPIm.d.ts +127 -0
  19. package/dist/chunks/{globals.BCtI_nQG.js → globals.BEpDe-k3.js} +5 -5
  20. package/dist/chunks/{index.C1f-_gvH.js → index.B8tIoLPT.js} +8 -3
  21. package/dist/chunks/{index.B8haHJlQ.js → index.D7Ny8f_s.js} +2 -2
  22. package/dist/chunks/{index.BmFFzXX_.js → index.uXkkC4xl.js} +1 -2
  23. package/dist/chunks/{mocker.cRtM890J.d.ts → mocker.d.BE_2ls6u.d.ts} +6 -6
  24. package/dist/chunks/reporters.d.CqBhtcTq.d.ts +3006 -0
  25. package/dist/chunks/{runBaseTests.9XCQcSZC.js → runBaseTests.BVrL_ow3.js} +9 -9
  26. package/dist/chunks/{setup-common.wObu9a36.js → setup-common.CPvtqi8q.js} +25 -2
  27. package/dist/chunks/{suite.qtkXWc6R.d.ts → suite.d.FvehnV49.d.ts} +1 -1
  28. package/dist/chunks/{typechecker.cZ0LjdSi.js → typechecker.BlF3eHsb.js} +2 -7
  29. package/dist/chunks/{vi.DT3m61kS.js → vi.nSCvwQ7l.js} +4 -4
  30. package/dist/chunks/vite.d.BUZTGxQ3.d.ts +11 -0
  31. package/dist/chunks/{vm.6kNys9FN.js → vm.jEFQDlX_.js} +1 -1
  32. package/dist/chunks/{worker.DaAIyCKm.d.ts → worker.d.C58isfFm.d.ts} +62 -62
  33. package/dist/chunks/{worker.B2JXutr8.d.ts → worker.d.CSFlSYJg.d.ts} +2 -2
  34. package/dist/cli.js +2 -2
  35. package/dist/config.d.ts +48 -45
  36. package/dist/config.js +6 -123
  37. package/dist/coverage.d.ts +82 -79
  38. package/dist/coverage.js +19 -469
  39. package/dist/environments.d.ts +11 -11
  40. package/dist/execute.d.ts +109 -109
  41. package/dist/execute.js +1 -1
  42. package/dist/index.d.ts +414 -412
  43. package/dist/index.js +4 -4
  44. package/dist/node.d.ts +51 -48
  45. package/dist/node.js +13 -10
  46. package/dist/reporters.d.ts +7 -4
  47. package/dist/reporters.js +3 -2
  48. package/dist/runners.d.ts +28 -28
  49. package/dist/runners.js +3 -4
  50. package/dist/snapshot.d.ts +2 -2
  51. package/dist/suite.d.ts +2 -2
  52. package/dist/suite.js +1 -1
  53. package/dist/workers/forks.js +2 -2
  54. package/dist/workers/runVmTests.js +9 -9
  55. package/dist/workers/threads.js +2 -2
  56. package/dist/workers/vmForks.js +2 -2
  57. package/dist/workers/vmThreads.js +2 -2
  58. package/dist/workers.d.ts +13 -13
  59. package/dist/workers.js +3 -3
  60. package/package.json +12 -12
  61. package/dist/chunks/config.BRtC-JeT.d.ts +0 -215
  62. package/dist/chunks/environment.d8YfPkTm.d.ts +0 -173
  63. package/dist/chunks/global.CnI8_G5V.d.ts +0 -133
  64. package/dist/chunks/reporters.QZ837uWx.d.ts +0 -3051
  65. package/dist/chunks/spy.Cf_4R5Oe.js +0 -22
  66. package/dist/chunks/vite.vM3UZq1q.d.ts +0 -11
@@ -0,0 +1,3006 @@
1
+ import { Task, Suite, File, TaskMeta, TaskResultPack, SequenceSetupFiles, SequenceHooks, CancelReason } from '@vitest/runner';
2
+ import { b as Awaitable, U as UserConsoleLog, c as Arrayable$1, A as AfterSuiteRunMeta, f as EnvironmentOptions, P as ProvidedContext } from './environment.d.C8UItCbf.js';
3
+ import { ParsedStack, TestError, SerializedError, ErrorWithDiff, Arrayable, Awaitable as Awaitable$1 } from '@vitest/utils';
4
+ import { Writable } from 'node:stream';
5
+ import { TransformResult as TransformResult$1, UserConfig as UserConfig$1, DepOptimizationConfig, ServerOptions, ConfigEnv, AliasOptions, ViteDevServer, ModuleNode } from 'vite';
6
+ import { Console } from 'node:console';
7
+ import { StackTraceParserOptions } from '@vitest/utils/source-map';
8
+ import { a as SerializedConfig, F as FakeTimerInstallOpts } from './config.d.DevWltVl.js';
9
+ import { PrettyFormatOptions } from '@vitest/pretty-format';
10
+ import { SnapshotSummary, SnapshotStateOptions } from '@vitest/snapshot';
11
+ import { SerializedDiffOptions } from '@vitest/utils/diff';
12
+ import { ViteNodeServerOptions } from 'vite-node';
13
+ import * as chai from 'chai';
14
+ import { B as BenchmarkResult } from './benchmark.d.BwvBVTda.js';
15
+ import { a as RuntimeCoverageProviderModule } from './coverage.d.S9RMNXIe.js';
16
+ import { SnapshotManager } from '@vitest/snapshot/manager';
17
+ import { Stats } from 'node:fs';
18
+
19
+ declare class TypeCheckError extends Error {
20
+ message: string;
21
+ stacks: ParsedStack[];
22
+ name: string;
23
+ constructor(message: string, stacks: ParsedStack[]);
24
+ }
25
+
26
+ interface ErrorOptions {
27
+ type?: string;
28
+ fullStack?: boolean;
29
+ project?: TestProject;
30
+ verbose?: boolean;
31
+ screenshotPaths?: string[];
32
+ task?: Task;
33
+ showCodeFrame?: boolean;
34
+ }
35
+ type Listener = () => void;
36
+ declare class Logger {
37
+ ctx: Vitest;
38
+ outputStream: NodeJS.WriteStream | Writable;
39
+ errorStream: NodeJS.WriteStream | Writable;
40
+ private _clearScreenPending;
41
+ private _highlights;
42
+ private cleanupListeners;
43
+ console: Console;
44
+ constructor(ctx: Vitest, outputStream?: NodeJS.WriteStream | Writable, errorStream?: NodeJS.WriteStream | Writable);
45
+ log(...args: any[]): void;
46
+ error(...args: any[]): void;
47
+ warn(...args: any[]): void;
48
+ clearFullScreen(message?: string): void;
49
+ clearScreen(message: string, force?: boolean): void;
50
+ private _clearScreen;
51
+ printError(err: unknown, options?: ErrorOptions): void;
52
+ clearHighlightCache(filename?: string): void;
53
+ highlight(filename: string, source: string): string;
54
+ printNoTestFound(filters?: string[]): void;
55
+ printBanner(): void;
56
+ printBrowserBanner(project: TestProject): void;
57
+ printUnhandledErrors(errors: unknown[]): void;
58
+ printSourceTypeErrors(errors: TypeCheckError[]): void;
59
+ getColumns(): number;
60
+ onTerminalCleanup(listener: Listener): void;
61
+ private addCleanupListeners;
62
+ private registerUnhandledRejection;
63
+ }
64
+
65
+ type SerializedTestSpecification = [project: {
66
+ name: string | undefined
67
+ root: string
68
+ }, file: string, options: {
69
+ pool: string
70
+ testLines?: number[] | undefined
71
+ }];
72
+
73
+ declare class ReportedTaskImplementation {
74
+ /**
75
+ * The project associated with the test or suite.
76
+ */
77
+ readonly project: TestProject;
78
+ /**
79
+ * Unique identifier.
80
+ * This ID is deterministic and will be the same for the same test across multiple runs.
81
+ * The ID is based on the project name, module url and test order.
82
+ */
83
+ readonly id: string;
84
+ /**
85
+ * Location in the module where the test or suite is defined.
86
+ */
87
+ readonly location: {
88
+ line: number
89
+ column: number
90
+ } | undefined;
91
+ /**
92
+ * Checks if the test did not fail the suite.
93
+ * If the test is not finished yet or was skipped, it will return `true`.
94
+ */
95
+ ok(): boolean;
96
+ }
97
+ declare class TestCase extends ReportedTaskImplementation {
98
+ #private;
99
+ readonly type = "test";
100
+ /**
101
+ * Direct reference to the test module where the test or suite is defined.
102
+ */
103
+ readonly module: TestModule;
104
+ /**
105
+ * Name of the test.
106
+ */
107
+ readonly name: string;
108
+ /**
109
+ * Options that the test was initiated with.
110
+ */
111
+ readonly options: TaskOptions;
112
+ /**
113
+ * Parent suite. If the test was called directly inside the module, the parent will be the module itself.
114
+ */
115
+ readonly parent: TestSuite | TestModule;
116
+ /**
117
+ * Full name of the test including all parent suites separated with `>`.
118
+ */
119
+ get fullName(): string;
120
+ /**
121
+ * Test results.
122
+ * - **pending**: Test was collected, but didn't finish running yet.
123
+ * - **passed**: Test passed successfully
124
+ * - **failed**: Test failed to execute
125
+ * - **skipped**: Test was skipped during collection or dynamically with `ctx.skip()`.
126
+ */
127
+ result(): TestResult;
128
+ /**
129
+ * Custom metadata that was attached to the test during its execution.
130
+ */
131
+ meta(): TaskMeta;
132
+ /**
133
+ * Useful information about the test like duration, memory usage, etc.
134
+ * Diagnostic is only available after the test has finished.
135
+ */
136
+ diagnostic(): TestDiagnostic | undefined;
137
+ }
138
+ declare class TestCollection {
139
+ #private;
140
+ constructor(task: Suite | File, project: TestProject);
141
+ /**
142
+ * Returns the test or suite at a specific index.
143
+ */
144
+ at(index: number): TestCase | TestSuite | undefined;
145
+ /**
146
+ * The number of tests and suites in the collection.
147
+ */
148
+ get size(): number;
149
+ /**
150
+ * Returns the collection in array form for easier manipulation.
151
+ */
152
+ array(): (TestCase | TestSuite)[];
153
+ /**
154
+ * Filters all tests that are part of this collection and its children.
155
+ */
156
+ allTests(state?: TestState): Generator<TestCase, undefined, void>;
157
+ /**
158
+ * Filters only the tests that are part of this collection.
159
+ */
160
+ tests(state?: TestState): Generator<TestCase, undefined, void>;
161
+ /**
162
+ * Filters only the suites that are part of this collection.
163
+ */
164
+ suites(): Generator<TestSuite, undefined, void>;
165
+ /**
166
+ * Filters all suites that are part of this collection and its children.
167
+ */
168
+ allSuites(): Generator<TestSuite, undefined, void>;
169
+ [Symbol.iterator](): Generator<TestSuite | TestCase, undefined, void>;
170
+ }
171
+
172
+ type ReportedHookContext = {
173
+ readonly name: "beforeAll" | "afterAll"
174
+ readonly entity: TestSuite | TestModule
175
+ } | {
176
+ readonly name: "beforeEach" | "afterEach"
177
+ readonly entity: TestCase
178
+ };
179
+ declare abstract class SuiteImplementation extends ReportedTaskImplementation {
180
+ /**
181
+ * Collection of suites and tests that are part of this suite.
182
+ */
183
+ readonly children: TestCollection;
184
+ /**
185
+ * Errors that happened outside of the test run during collection, like syntax errors.
186
+ */
187
+ errors(): SerializedError[];
188
+ }
189
+ declare class TestSuite extends SuiteImplementation {
190
+ #private;
191
+ readonly type = "suite";
192
+ /**
193
+ * Name of the test or the suite.
194
+ */
195
+ readonly name: string;
196
+ /**
197
+ * Direct reference to the test module where the test or suite is defined.
198
+ */
199
+ readonly module: TestModule;
200
+ /**
201
+ * Parent suite. If suite was called directly inside the module, the parent will be the module itself.
202
+ */
203
+ readonly parent: TestSuite | TestModule;
204
+ /**
205
+ * Options that suite was initiated with.
206
+ */
207
+ readonly options: TaskOptions;
208
+ /**
209
+ * Checks if the suite has any failed tests.
210
+ * This will also return `false` if suite failed during collection.
211
+ */
212
+ ok: () => boolean;
213
+ /**
214
+ * Checks the running state of the suite.
215
+ */
216
+ state(): TestSuiteState;
217
+ /**
218
+ * Full name of the suite including all parent suites separated with `>`.
219
+ */
220
+ get fullName(): string;
221
+ }
222
+ declare class TestModule extends SuiteImplementation {
223
+ readonly location: undefined;
224
+ readonly type = "module";
225
+ /**
226
+ * This is usually an absolute UNIX file path.
227
+ * It can be a virtual ID if the file is not on the disk.
228
+ * This value corresponds to the ID in the Vite's module graph.
229
+ */
230
+ readonly moduleId: string;
231
+ /**
232
+ * Checks the running state of the test file.
233
+ */
234
+ state(): TestModuleState;
235
+ /**
236
+ * Checks if the module has any failed tests.
237
+ * This will also return `false` if module failed during collection.
238
+ */
239
+ ok: () => boolean;
240
+ /**
241
+ * Useful information about the module like duration, memory usage, etc.
242
+ * If the module was not executed yet, all diagnostic values will return `0`.
243
+ */
244
+ diagnostic(): ModuleDiagnostic;
245
+ }
246
+ interface TaskOptions {
247
+ readonly each: boolean | undefined;
248
+ readonly fails: boolean | undefined;
249
+ readonly concurrent: boolean | undefined;
250
+ readonly shuffle: boolean | undefined;
251
+ readonly retry: number | undefined;
252
+ readonly repeats: number | undefined;
253
+ readonly mode: "run" | "only" | "skip" | "todo";
254
+ }
255
+ type TestSuiteState = "skipped" | "pending" | "failed" | "passed";
256
+ type TestModuleState = TestSuiteState | "queued";
257
+ type TestState = TestResult["state"];
258
+ type TestResult = TestResultPassed | TestResultFailed | TestResultSkipped | TestResultPending;
259
+ interface TestResultPending {
260
+ /**
261
+ * The test was collected, but didn't finish running yet.
262
+ */
263
+ readonly state: "pending";
264
+ /**
265
+ * Pending tests have no errors.
266
+ */
267
+ readonly errors: undefined;
268
+ }
269
+ interface TestResultPassed {
270
+ /**
271
+ * The test passed successfully.
272
+ */
273
+ readonly state: "passed";
274
+ /**
275
+ * Errors that were thrown during the test execution.
276
+ *
277
+ * **Note**: If test was retried successfully, errors will still be reported.
278
+ */
279
+ readonly errors: ReadonlyArray<TestError> | undefined;
280
+ }
281
+ interface TestResultFailed {
282
+ /**
283
+ * The test failed to execute.
284
+ */
285
+ readonly state: "failed";
286
+ /**
287
+ * Errors that were thrown during the test execution.
288
+ */
289
+ readonly errors: ReadonlyArray<TestError>;
290
+ }
291
+ interface TestResultSkipped {
292
+ /**
293
+ * The test was skipped with `only` (on another test), `skip` or `todo` flag.
294
+ * You can see which one was used in the `options.mode` option.
295
+ */
296
+ readonly state: "skipped";
297
+ /**
298
+ * Skipped tests have no errors.
299
+ */
300
+ readonly errors: undefined;
301
+ /**
302
+ * A custom note passed down to `ctx.skip(note)`.
303
+ */
304
+ readonly note: string | undefined;
305
+ }
306
+ interface TestDiagnostic {
307
+ /**
308
+ * If the duration of the test is above `slowTestThreshold`.
309
+ */
310
+ readonly slow: boolean;
311
+ /**
312
+ * The amount of memory used by the test in bytes.
313
+ * This value is only available if the test was executed with `logHeapUsage` flag.
314
+ */
315
+ readonly heap: number | undefined;
316
+ /**
317
+ * The time it takes to execute the test in ms.
318
+ */
319
+ readonly duration: number;
320
+ /**
321
+ * The time in ms when the test started.
322
+ */
323
+ readonly startTime: number;
324
+ /**
325
+ * The amount of times the test was retried.
326
+ */
327
+ readonly retryCount: number;
328
+ /**
329
+ * The amount of times the test was repeated as configured by `repeats` option.
330
+ * This value can be lower if the test failed during the repeat and no `retry` is configured.
331
+ */
332
+ readonly repeatCount: number;
333
+ /**
334
+ * If test passed on a second retry.
335
+ */
336
+ readonly flaky: boolean;
337
+ }
338
+ interface ModuleDiagnostic {
339
+ /**
340
+ * The time it takes to import and initiate an environment.
341
+ */
342
+ readonly environmentSetupDuration: number;
343
+ /**
344
+ * The time it takes Vitest to setup test harness (runner, mocks, etc.).
345
+ */
346
+ readonly prepareDuration: number;
347
+ /**
348
+ * The time it takes to import the test module.
349
+ * This includes importing everything in the module and executing suite callbacks.
350
+ */
351
+ readonly collectDuration: number;
352
+ /**
353
+ * The time it takes to import the setup module.
354
+ */
355
+ readonly setupDuration: number;
356
+ /**
357
+ * Accumulated duration of all tests and hooks in the module.
358
+ */
359
+ readonly duration: number;
360
+ }
361
+
362
+ type BuiltinPool = "browser" | "threads" | "forks" | "vmThreads" | "vmForks" | "typescript";
363
+ type Pool = BuiltinPool | (string & {});
364
+ interface PoolOptions extends Record<string, unknown> {
365
+ /**
366
+ * Run tests in `node:worker_threads`.
367
+ *
368
+ * Test isolation (when enabled) is done by spawning a new thread for each test file.
369
+ *
370
+ * This pool is used by default.
371
+ */
372
+ threads?: ThreadsOptions & WorkerContextOptions;
373
+ /**
374
+ * Run tests in `node:child_process` using [`fork()`](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options)
375
+ *
376
+ * Test isolation (when enabled) is done by spawning a new child process for each test file.
377
+ */
378
+ forks?: ForksOptions & WorkerContextOptions;
379
+ /**
380
+ * Run tests in isolated `node:vm`.
381
+ * Test files are run parallel using `node:worker_threads`.
382
+ *
383
+ * This makes tests run faster, but VM module is unstable. Your tests might leak memory.
384
+ */
385
+ vmThreads?: ThreadsOptions & VmOptions;
386
+ /**
387
+ * Run tests in isolated `node:vm`.
388
+ *
389
+ * Test files are run parallel using `node:child_process` [`fork()`](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options)
390
+ *
391
+ * This makes tests run faster, but VM module is unstable. Your tests might leak memory.
392
+ */
393
+ vmForks?: ForksOptions & VmOptions;
394
+ }
395
+ interface ResolvedPoolOptions extends PoolOptions {
396
+ threads?: ResolvedThreadsOptions & WorkerContextOptions;
397
+ forks?: ResolvedForksOptions & WorkerContextOptions;
398
+ vmThreads?: ResolvedThreadsOptions & VmOptions;
399
+ vmForks?: ResolvedForksOptions & VmOptions;
400
+ }
401
+ interface ThreadsOptions {
402
+ /** Minimum amount of threads to use */
403
+ minThreads?: number | string;
404
+ /** Maximum amount of threads to use */
405
+ maxThreads?: number | string;
406
+ /**
407
+ * Run tests inside a single thread.
408
+ *
409
+ * @default false
410
+ */
411
+ singleThread?: boolean;
412
+ /**
413
+ * Use Atomics to synchronize threads
414
+ *
415
+ * This can improve performance in some cases, but might cause segfault in older Node versions.
416
+ *
417
+ * @default false
418
+ */
419
+ useAtomics?: boolean;
420
+ }
421
+ interface ResolvedThreadsOptions extends ThreadsOptions {
422
+ minThreads?: number;
423
+ maxThreads?: number;
424
+ }
425
+ interface ForksOptions {
426
+ /** Minimum amount of child processes to use */
427
+ minForks?: number | string;
428
+ /** Maximum amount of child processes to use */
429
+ maxForks?: number | string;
430
+ /**
431
+ * Run tests inside a single fork.
432
+ *
433
+ * @default false
434
+ */
435
+ singleFork?: boolean;
436
+ }
437
+ interface ResolvedForksOptions extends ForksOptions {
438
+ minForks?: number;
439
+ maxForks?: number;
440
+ }
441
+ interface WorkerContextOptions {
442
+ /**
443
+ * Isolate test environment by recycling `worker_threads` or `child_process` after each test
444
+ *
445
+ * @default true
446
+ */
447
+ isolate?: boolean;
448
+ /**
449
+ * Pass additional arguments to `node` process when spawning `worker_threads` or `child_process`.
450
+ *
451
+ * See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
452
+ *
453
+ * Set to `process.execArgv` to pass all arguments of the current process.
454
+ *
455
+ * Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
456
+ *
457
+ * @default [] // no execution arguments are passed
458
+ */
459
+ execArgv?: string[];
460
+ }
461
+ interface VmOptions {
462
+ /**
463
+ * Specifies the memory limit for `worker_thread` or `child_process` before they are recycled.
464
+ * If you see memory leaks, try to tinker this value.
465
+ */
466
+ memoryLimit?: string | number;
467
+ /** Isolation is always enabled */
468
+ isolate?: true;
469
+ /**
470
+ * Pass additional arguments to `node` process when spawning `worker_threads` or `child_process`.
471
+ *
472
+ * See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
473
+ *
474
+ * Set to `process.execArgv` to pass all arguments of the current process.
475
+ *
476
+ * Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
477
+ *
478
+ * @default [] // no execution arguments are passed
479
+ */
480
+ execArgv?: string[];
481
+ }
482
+
483
+ declare class TestSpecification {
484
+ /**
485
+ * @deprecated use `project` instead
486
+ */
487
+ readonly 0: TestProject;
488
+ /**
489
+ * @deprecated use `moduleId` instead
490
+ */
491
+ readonly 1: string;
492
+ /**
493
+ * @deprecated use `pool` instead
494
+ */
495
+ readonly 2: {
496
+ pool: Pool
497
+ };
498
+ /**
499
+ * The task ID associated with the test module.
500
+ */
501
+ readonly taskId: string;
502
+ /**
503
+ * The test project that the module belongs to.
504
+ */
505
+ readonly project: TestProject;
506
+ /**
507
+ * The ID of the module in the Vite module graph. It is usually an absolute file path.
508
+ */
509
+ readonly moduleId: string;
510
+ /**
511
+ * The current test pool. It's possible to have multiple pools in a single test project with `poolMatchGlob` and `typecheck.enabled`.
512
+ * @experimental In Vitest 4, the project will only support a single pool and this property will be removed.
513
+ */
514
+ readonly pool: Pool;
515
+ /**
516
+ * Line numbers of the test locations to run.
517
+ */
518
+ readonly testLines: number[] | undefined;
519
+ constructor(project: TestProject, moduleId: string, pool: Pool, testLines?: number[] | undefined);
520
+ /**
521
+ * Test module associated with the specification.
522
+ */
523
+ get testModule(): TestModule | undefined;
524
+ toJSON(): SerializedTestSpecification;
525
+ /**
526
+ * for backwards compatibility
527
+ * @deprecated
528
+ */
529
+ [Symbol.iterator](): Generator<string | TestProject, void, unknown>;
530
+ }
531
+
532
+ type TestRunEndReason = "passed" | "interrupted" | "failed";
533
+ interface Reporter {
534
+ onInit?: (vitest: Vitest) => void;
535
+ /**
536
+ * Called when the project initiated the browser instance.
537
+ * project.browser will always be defined.
538
+ * @experimental
539
+ */
540
+ onBrowserInit?: (project: TestProject) => Awaitable<void>;
541
+ /**
542
+ * @deprecated use `onTestRunStart` instead
543
+ */
544
+ onPathsCollected?: (paths?: string[]) => Awaitable<void>;
545
+ /**
546
+ * @deprecated use `onTestRunStart` instead
547
+ */
548
+ onSpecsCollected?: (specs?: SerializedTestSpecification[]) => Awaitable<void>;
549
+ /**
550
+ * @deprecated use `onTestModuleCollected` instead
551
+ */
552
+ onCollected?: (files: File[]) => Awaitable<void>;
553
+ /**
554
+ * @deprecated use `onTestRunEnd` instead
555
+ */
556
+ onFinished?: (files: File[], errors: unknown[], coverage?: unknown) => Awaitable<void>;
557
+ /**
558
+ * @deprecated use `onTestModuleQueued`, `onTestModuleStart`, `onTestModuleEnd`, `onTestCaseReady`, `onTestCaseResult` instead
559
+ */
560
+ onTaskUpdate?: (packs: TaskResultPack[]) => Awaitable<void>;
561
+ onTestRemoved?: (trigger?: string) => Awaitable<void>;
562
+ onWatcherStart?: (files?: File[], errors?: unknown[]) => Awaitable<void>;
563
+ onWatcherRerun?: (files: string[], trigger?: string) => Awaitable<void>;
564
+ onServerRestart?: (reason?: string) => Awaitable<void>;
565
+ onUserConsoleLog?: (log: UserConsoleLog) => Awaitable<void>;
566
+ onProcessTimeout?: () => Awaitable<void>;
567
+ /**
568
+ * Called when the new test run starts.
569
+ */
570
+ onTestRunStart?: (specifications: ReadonlyArray<TestSpecification>) => Awaitable<void>;
571
+ /**
572
+ * Called when the test run is finished.
573
+ */
574
+ onTestRunEnd?: (testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>, reason: TestRunEndReason) => Awaitable<void>;
575
+ /**
576
+ * Called when the module is enqueued for testing. The file itself is not loaded yet.
577
+ */
578
+ onTestModuleQueued?: (testModule: TestModule) => Awaitable<void>;
579
+ /**
580
+ * Called when the test file is loaded and the module is ready to run tests.
581
+ */
582
+ onTestModuleCollected?: (testModule: TestModule) => Awaitable<void>;
583
+ /**
584
+ * Called when starting to run tests of the test file
585
+ */
586
+ onTestModuleStart?: (testModule: TestModule) => Awaitable<void>;
587
+ /**
588
+ * Called when all tests of the test file have finished running.
589
+ */
590
+ onTestModuleEnd?: (testModule: TestModule) => Awaitable<void>;
591
+ /**
592
+ * Called when test case is ready to run.
593
+ * Called before the `beforeEach` hooks for the test are run.
594
+ */
595
+ onTestCaseReady?: (testCase: TestCase) => Awaitable<void>;
596
+ /**
597
+ * Called after the test and its hooks are finished running.
598
+ * The `result()` cannot be `pending`.
599
+ */
600
+ onTestCaseResult?: (testCase: TestCase) => Awaitable<void>;
601
+ /**
602
+ * Called when test suite is ready to run.
603
+ * Called before the `beforeAll` hooks for the test are run.
604
+ */
605
+ onTestSuiteReady?: (testSuite: TestSuite) => Awaitable<void>;
606
+ /**
607
+ * Called after the test suite and its hooks are finished running.
608
+ * The `state` cannot be `pending`.
609
+ */
610
+ onTestSuiteResult?: (testSuite: TestSuite) => Awaitable<void>;
611
+ /**
612
+ * Called before the hook starts to run.
613
+ */
614
+ onHookStart?: (hook: ReportedHookContext) => Awaitable<void>;
615
+ /**
616
+ * Called after the hook finished running.
617
+ */
618
+ onHookEnd?: (hook: ReportedHookContext) => Awaitable<void>;
619
+ onCoverage?: (coverage: unknown) => Awaitable<void>;
620
+ }
621
+
622
+ interface BaseOptions {
623
+ isTTY?: boolean;
624
+ }
625
+ declare abstract class BaseReporter implements Reporter {
626
+ start: number;
627
+ end: number;
628
+ watchFilters?: string[];
629
+ failedUnwatchedFiles: Task[];
630
+ isTTY: boolean;
631
+ ctx: Vitest;
632
+ renderSucceed: boolean;
633
+ protected verbose: boolean;
634
+ private _filesInWatchMode;
635
+ private _timeStart;
636
+ constructor(options?: BaseOptions);
637
+ onInit(ctx: Vitest): void;
638
+ log(...messages: any): void;
639
+ error(...messages: any): void;
640
+ relative(path: string): string;
641
+ onFinished(files?: File[], errors?: unknown[]): void;
642
+ onTaskUpdate(packs: TaskResultPack[]): void;
643
+ /**
644
+ * Callback invoked with a single `Task` from `onTaskUpdate`
645
+ */
646
+ protected printTask(task: Task): void;
647
+ protected printSuite(_task: Task): void;
648
+ protected getTestName(test: Task, separator?: string): string;
649
+ protected formatShortError(error: ErrorWithDiff): string;
650
+ protected getTestIndentation(_test: Task): string;
651
+ private getDurationPrefix;
652
+ onWatcherStart(files?: File[], errors?: unknown[]): void;
653
+ onWatcherRerun(files: string[], trigger?: string): void;
654
+ onUserConsoleLog(log: UserConsoleLog): void;
655
+ onTestRemoved(trigger?: string): void;
656
+ shouldLog(log: UserConsoleLog): boolean;
657
+ onServerRestart(reason?: string): void;
658
+ reportSummary(files: File[], errors: unknown[]): void;
659
+ reportTestSummary(files: File[], errors: unknown[]): void;
660
+ private printErrorsSummary;
661
+ reportBenchmarkSummary(files: File[]): void;
662
+ private printTaskErrors;
663
+ }
664
+
665
+ interface BlobOptions {
666
+ outputFile?: string;
667
+ }
668
+ declare class BlobReporter implements Reporter {
669
+ ctx: Vitest;
670
+ options: BlobOptions;
671
+ constructor(options: BlobOptions);
672
+ onInit(ctx: Vitest): void;
673
+ onFinished(files: File[] | undefined, errors: unknown[] | undefined, coverage: unknown): Promise<void>;
674
+ }
675
+
676
+ interface DefaultReporterOptions extends BaseOptions {
677
+ summary?: boolean;
678
+ }
679
+ declare class DefaultReporter extends BaseReporter {
680
+ private options;
681
+ private summary?;
682
+ constructor(options?: DefaultReporterOptions);
683
+ onTestRunStart(specifications: ReadonlyArray<TestSpecification>): void;
684
+ onTestModuleQueued(file: TestModule): void;
685
+ onTestModuleCollected(module: TestModule): void;
686
+ onTestModuleEnd(module: TestModule): void;
687
+ onTestCaseReady(test: TestCase): void;
688
+ onTestCaseResult(test: TestCase): void;
689
+ onHookStart(hook: ReportedHookContext): void;
690
+ onHookEnd(hook: ReportedHookContext): void;
691
+ onInit(ctx: Vitest): void;
692
+ onPathsCollected(paths?: string[]): void;
693
+ onTestRunEnd(): void;
694
+ }
695
+
696
+ interface HTMLOptions {
697
+ outputFile?: string;
698
+ }
699
+
700
+ interface CoverageSummaryData {
701
+ lines: Totals;
702
+ statements: Totals;
703
+ branches: Totals;
704
+ functions: Totals;
705
+ }
706
+
707
+ declare class CoverageSummary {
708
+ constructor(data: CoverageSummary | CoverageSummaryData);
709
+ merge(obj: CoverageSummary): CoverageSummary;
710
+ toJSON(): CoverageSummaryData;
711
+ isEmpty(): boolean;
712
+ data: CoverageSummaryData;
713
+ lines: Totals;
714
+ statements: Totals;
715
+ branches: Totals;
716
+ functions: Totals;
717
+ }
718
+
719
+ interface CoverageMapData {
720
+ [key: string]: FileCoverage | FileCoverageData;
721
+ }
722
+
723
+ declare class CoverageMap {
724
+ constructor(data: CoverageMapData | CoverageMap);
725
+ addFileCoverage(pathOrObject: string | FileCoverage | FileCoverageData): void;
726
+ files(): string[];
727
+ fileCoverageFor(filename: string): FileCoverage;
728
+ filter(callback: (key: string) => boolean): void;
729
+ getCoverageSummary(): CoverageSummary;
730
+ merge(data: CoverageMapData | CoverageMap): void;
731
+ toJSON(): CoverageMapData;
732
+ data: CoverageMapData;
733
+ }
734
+
735
+ interface Location {
736
+ line: number;
737
+ column: number;
738
+ }
739
+
740
+ interface Range {
741
+ start: Location;
742
+ end: Location;
743
+ }
744
+
745
+ interface BranchMapping {
746
+ loc: Range;
747
+ type: string;
748
+ locations: Range[];
749
+ line: number;
750
+ }
751
+
752
+ interface FunctionMapping {
753
+ name: string;
754
+ decl: Range;
755
+ loc: Range;
756
+ line: number;
757
+ }
758
+
759
+ interface FileCoverageData {
760
+ path: string;
761
+ statementMap: { [key: string]: Range };
762
+ fnMap: { [key: string]: FunctionMapping };
763
+ branchMap: { [key: string]: BranchMapping };
764
+ s: { [key: string]: number };
765
+ f: { [key: string]: number };
766
+ b: { [key: string]: number[] };
767
+ }
768
+
769
+ interface Totals {
770
+ total: number;
771
+ covered: number;
772
+ skipped: number;
773
+ pct: number;
774
+ }
775
+
776
+ interface Coverage {
777
+ covered: number;
778
+ total: number;
779
+ coverage: number;
780
+ }
781
+
782
+ declare class FileCoverage implements FileCoverageData {
783
+ constructor(data: string | FileCoverage | FileCoverageData);
784
+ merge(other: FileCoverageData): void;
785
+ getBranchCoverageByLine(): { [line: number]: Coverage };
786
+ getLineCoverage(): { [line: number]: number };
787
+ getUncoveredLines(): number[];
788
+ resetHits(): void;
789
+ computeBranchTotals(): Totals;
790
+ computeSimpleTotals(): Totals;
791
+ toSummary(): CoverageSummary;
792
+ toJSON(): object;
793
+
794
+ data: FileCoverageData;
795
+ path: string;
796
+ statementMap: { [key: string]: Range };
797
+ fnMap: { [key: string]: FunctionMapping };
798
+ branchMap: { [key: string]: BranchMapping };
799
+ s: { [key: string]: number };
800
+ f: { [key: string]: number };
801
+ b: { [key: string]: number[] };
802
+ }
803
+
804
+ type Status = "passed" | "failed" | "skipped" | "pending" | "todo" | "disabled";
805
+ type Milliseconds = number;
806
+ interface Callsite {
807
+ line: number;
808
+ column: number;
809
+ }
810
+ interface JsonAssertionResult {
811
+ ancestorTitles: Array<string>;
812
+ fullName: string;
813
+ status: Status;
814
+ title: string;
815
+ meta: TaskMeta;
816
+ duration?: Milliseconds | null;
817
+ failureMessages: Array<string> | null;
818
+ location?: Callsite | null;
819
+ }
820
+ interface JsonTestResult {
821
+ message: string;
822
+ name: string;
823
+ status: "failed" | "passed";
824
+ startTime: number;
825
+ endTime: number;
826
+ assertionResults: Array<JsonAssertionResult>;
827
+ }
828
+ interface JsonTestResults {
829
+ numFailedTests: number;
830
+ numFailedTestSuites: number;
831
+ numPassedTests: number;
832
+ numPassedTestSuites: number;
833
+ numPendingTests: number;
834
+ numPendingTestSuites: number;
835
+ numTodoTests: number;
836
+ numTotalTests: number;
837
+ numTotalTestSuites: number;
838
+ startTime: number;
839
+ success: boolean;
840
+ testResults: Array<JsonTestResult>;
841
+ snapshot: SnapshotSummary;
842
+ coverageMap?: CoverageMap | null | undefined;
843
+ }
844
+ interface JsonOptions$1 {
845
+ outputFile?: string;
846
+ }
847
+ declare class JsonReporter implements Reporter {
848
+ start: number;
849
+ ctx: Vitest;
850
+ options: JsonOptions$1;
851
+ constructor(options: JsonOptions$1);
852
+ onInit(ctx: Vitest): void;
853
+ protected logTasks(files: File[], coverageMap?: CoverageMap | null): Promise<void>;
854
+ onFinished(files?: File[], _errors?: unknown[], coverageMap?: unknown): Promise<void>;
855
+ /**
856
+ * Writes the report to an output file if specified in the config,
857
+ * or logs it to the console otherwise.
858
+ * @param report
859
+ */
860
+ writeReport(report: string): Promise<void>;
861
+ }
862
+
863
+ interface ClassnameTemplateVariables {
864
+ filename: string;
865
+ filepath: string;
866
+ }
867
+ interface JUnitOptions {
868
+ outputFile?: string;
869
+ /** @deprecated Use `classnameTemplate` instead. */
870
+ classname?: string;
871
+ /**
872
+ * Template for the classname attribute. Can be either a string or a function. The string can contain placeholders {filename} and {filepath}.
873
+ */
874
+ classnameTemplate?: string | ((classnameVariables: ClassnameTemplateVariables) => string);
875
+ suiteName?: string;
876
+ /**
877
+ * Write <system-out> and <system-err> for console output
878
+ * @default true
879
+ */
880
+ includeConsoleOutput?: boolean;
881
+ /**
882
+ * Add <testcase file="..."> attribute (validated on CIRCLE CI and GitLab CI)
883
+ * @default false
884
+ */
885
+ addFileAttribute?: boolean;
886
+ }
887
+ declare class JUnitReporter implements Reporter {
888
+ private ctx;
889
+ private reportFile?;
890
+ private baseLog;
891
+ private logger;
892
+ private _timeStart;
893
+ private fileFd?;
894
+ private options;
895
+ constructor(options: JUnitOptions);
896
+ onInit(ctx: Vitest): Promise<void>;
897
+ writeElement(name: string, attrs: Record<string, any>, children: () => Promise<void>): Promise<void>;
898
+ writeLogs(task: Task, type: "err" | "out"): Promise<void>;
899
+ writeTasks(tasks: Task[], filename: string): Promise<void>;
900
+ onFinished(files?: File[]): Promise<void>;
901
+ }
902
+
903
+ declare class BasicReporter extends BaseReporter {
904
+ constructor();
905
+ onInit(ctx: Vitest): void;
906
+ reportSummary(files: File[], errors: unknown[]): void;
907
+ }
908
+
909
+ declare class DotReporter extends BaseReporter {
910
+ private renderer?;
911
+ private tests;
912
+ private finishedTests;
913
+ onInit(ctx: Vitest): void;
914
+ printTask(task: Task): void;
915
+ onWatcherRerun(files: string[], trigger?: string): void;
916
+ onFinished(files?: File[], errors?: unknown[]): void;
917
+ onTestModuleCollected(module: TestModule): void;
918
+ onTestCaseReady(test: TestCase): void;
919
+ onTestCaseResult(test: TestCase): void;
920
+ onTestModuleEnd(): void;
921
+ private createSummary;
922
+ }
923
+
924
+ declare class GithubActionsReporter implements Reporter {
925
+ ctx: Vitest;
926
+ onInit(ctx: Vitest): void;
927
+ onFinished(files?: File[], errors?: unknown[]): void;
928
+ }
929
+
930
+ declare class HangingProcessReporter implements Reporter {
931
+ whyRunning: (() => void) | undefined;
932
+ onInit(): void;
933
+ onProcessTimeout(): void;
934
+ }
935
+
936
+ declare class TapReporter implements Reporter {
937
+ protected ctx: Vitest;
938
+ private logger;
939
+ onInit(ctx: Vitest): void;
940
+ static getComment(task: Task): string;
941
+ private logErrorDetails;
942
+ protected logTasks(tasks: Task[]): void;
943
+ onFinished(files?: File[]): void;
944
+ }
945
+
946
+ declare class TapFlatReporter extends TapReporter {
947
+ onInit(ctx: Vitest): void;
948
+ onFinished(files?: File[]): void;
949
+ }
950
+
951
+ declare class VerboseReporter extends DefaultReporter {
952
+ protected verbose: boolean;
953
+ renderSucceed: boolean;
954
+ printTask(task: Task): void;
955
+ protected printSuite(task: Task): void;
956
+ protected getTestName(test: Task): string;
957
+ protected getTestIndentation(test: Task): string;
958
+ protected formatShortError(): string;
959
+ }
960
+
961
+ type FormattedBenchmarkResult = BenchmarkResult & {
962
+ id: string
963
+ };
964
+
965
+ declare function renderTable(options: {
966
+ tasks: Task[]
967
+ level: number
968
+ shallow?: boolean
969
+ showHeap: boolean
970
+ columns: number
971
+ slowTestThreshold: number
972
+ compare?: Record<Task["id"], FormattedBenchmarkResult>
973
+ }): string;
974
+
975
+ declare class BenchmarkReporter extends DefaultReporter {
976
+ compare?: Parameters<typeof renderTable>[0]["compare"];
977
+ onInit(ctx: Vitest): Promise<void>;
978
+ onTaskUpdate(packs: TaskResultPack[]): void;
979
+ printTask(task: Task): void;
980
+ onFinished(files?: File[], errors?: unknown[]): Promise<void>;
981
+ }
982
+
983
+ declare class VerboseBenchmarkReporter extends BenchmarkReporter {
984
+ protected verbose: boolean;
985
+ }
986
+
987
+ declare const BenchmarkReportsMap: {
988
+ default: typeof BenchmarkReporter
989
+ verbose: typeof VerboseBenchmarkReporter
990
+ };
991
+ type BenchmarkBuiltinReporters = keyof typeof BenchmarkReportsMap;
992
+
993
+ declare const ReportersMap: {
994
+ "default": typeof DefaultReporter
995
+ "basic": typeof BasicReporter
996
+ "blob": typeof BlobReporter
997
+ "verbose": typeof VerboseReporter
998
+ "dot": typeof DotReporter
999
+ "json": typeof JsonReporter
1000
+ "tap": typeof TapReporter
1001
+ "tap-flat": typeof TapFlatReporter
1002
+ "junit": typeof JUnitReporter
1003
+ "hanging-process": typeof HangingProcessReporter
1004
+ "github-actions": typeof GithubActionsReporter
1005
+ };
1006
+ type BuiltinReporters = keyof typeof ReportersMap;
1007
+ interface BuiltinReporterOptions {
1008
+ "default": DefaultReporterOptions;
1009
+ "basic": BaseOptions;
1010
+ "verbose": DefaultReporterOptions;
1011
+ "dot": BaseOptions;
1012
+ "json": JsonOptions$1;
1013
+ "blob": BlobOptions;
1014
+ "tap": never;
1015
+ "tap-flat": never;
1016
+ "junit": JUnitOptions;
1017
+ "hanging-process": never;
1018
+ "html": HTMLOptions;
1019
+ }
1020
+
1021
+ type ChaiConfig = Omit<Partial<typeof chai.config>, "useProxy" | "proxyExcludedKeys">;
1022
+
1023
+ interface TestSequencer {
1024
+ /**
1025
+ * Slicing tests into shards. Will be run before `sort`.
1026
+ * Only run, if `shard` is defined.
1027
+ */
1028
+ shard: (files: TestSpecification[]) => Awaitable<TestSpecification[]>;
1029
+ sort: (files: TestSpecification[]) => Awaitable<TestSpecification[]>;
1030
+ }
1031
+ interface TestSequencerConstructor {
1032
+ new (ctx: Vitest): TestSequencer;
1033
+ }
1034
+
1035
+ interface BenchmarkUserOptions {
1036
+ /**
1037
+ * Include globs for benchmark test files
1038
+ *
1039
+ * @default ['**\/*.{bench,benchmark}.?(c|m)[jt]s?(x)']
1040
+ */
1041
+ include?: string[];
1042
+ /**
1043
+ * Exclude globs for benchmark test files
1044
+ * @default ['**\/node_modules/**', '**\/dist/**', '**\/cypress/**', '**\/.{idea,git,cache,output,temp}/**', '**\/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*']
1045
+ */
1046
+ exclude?: string[];
1047
+ /**
1048
+ * Include globs for in-source benchmark test files
1049
+ *
1050
+ * @default []
1051
+ */
1052
+ includeSource?: string[];
1053
+ /**
1054
+ * Custom reporter for output. Can contain one or more built-in report names, reporter instances,
1055
+ * and/or paths to custom reporters
1056
+ *
1057
+ * @default ['default']
1058
+ */
1059
+ reporters?: Arrayable<BenchmarkBuiltinReporters | Reporter>;
1060
+ /**
1061
+ * @deprecated Use `benchmark.outputJson` instead
1062
+ */
1063
+ outputFile?: string | (Partial<Record<BenchmarkBuiltinReporters, string>> & Record<string, string>);
1064
+ /**
1065
+ * benchmark output file to compare against
1066
+ */
1067
+ compare?: string;
1068
+ /**
1069
+ * benchmark output file
1070
+ */
1071
+ outputJson?: string;
1072
+ /**
1073
+ * Include `samples` array of benchmark results for API or custom reporter usages.
1074
+ * This is disabled by default to reduce memory usage.
1075
+ * @default false
1076
+ */
1077
+ includeSamples?: boolean;
1078
+ }
1079
+
1080
+ interface Node {
1081
+ isRoot(): boolean;
1082
+ visit(visitor: Visitor, state: any): void;
1083
+ }
1084
+
1085
+ interface Visitor<N extends Node = Node> {
1086
+ onStart(root: N, state: any): void;
1087
+ onSummary(root: N, state: any): void;
1088
+ onDetail(root: N, state: any): void;
1089
+ onSummaryEnd(root: N, state: any): void;
1090
+ onEnd(root: N, state: any): void;
1091
+ }
1092
+
1093
+ interface FileOptions {
1094
+ file: string;
1095
+ }
1096
+
1097
+ interface ProjectOptions {
1098
+ projectRoot: string;
1099
+ }
1100
+
1101
+ interface ReportOptions {
1102
+ clover: CloverOptions;
1103
+ cobertura: CoberturaOptions;
1104
+ "html-spa": HtmlSpaOptions;
1105
+ html: HtmlOptions;
1106
+ json: JsonOptions;
1107
+ "json-summary": JsonSummaryOptions;
1108
+ lcov: LcovOptions;
1109
+ lcovonly: LcovOnlyOptions;
1110
+ none: never;
1111
+ teamcity: TeamcityOptions;
1112
+ text: TextOptions;
1113
+ "text-lcov": TextLcovOptions;
1114
+ "text-summary": TextSummaryOptions;
1115
+ }
1116
+
1117
+ interface CloverOptions extends FileOptions, ProjectOptions {}
1118
+
1119
+ interface CoberturaOptions extends FileOptions, ProjectOptions {}
1120
+
1121
+ interface HtmlSpaOptions extends HtmlOptions {
1122
+ metricsToShow: Array<"lines" | "branches" | "functions" | "statements">;
1123
+ }
1124
+ interface HtmlOptions {
1125
+ verbose: boolean;
1126
+ skipEmpty: boolean;
1127
+ subdir: string;
1128
+ linkMapper: LinkMapper;
1129
+ }
1130
+
1131
+ type JsonOptions = FileOptions;
1132
+ type JsonSummaryOptions = FileOptions;
1133
+
1134
+ interface LcovOptions extends FileOptions, ProjectOptions {}
1135
+ interface LcovOnlyOptions extends FileOptions, ProjectOptions {}
1136
+
1137
+ interface TeamcityOptions extends FileOptions {
1138
+ blockName: string;
1139
+ }
1140
+
1141
+ interface TextOptions extends FileOptions {
1142
+ maxCols: number;
1143
+ skipEmpty: boolean;
1144
+ skipFull: boolean;
1145
+ }
1146
+ type TextLcovOptions = ProjectOptions;
1147
+ type TextSummaryOptions = FileOptions;
1148
+
1149
+ interface LinkMapper {
1150
+ getPath(node: string | Node): string;
1151
+ relativePath(source: string | Node, target: string | Node): string;
1152
+ assetPath(node: Node, name: string): string;
1153
+ }
1154
+
1155
+ type TransformResult = string | Partial<TransformResult$1> | undefined | null | void;
1156
+ type CoverageResults = unknown;
1157
+ interface CoverageProvider {
1158
+ name: string;
1159
+ /** Called when provider is being initialized before tests run */
1160
+ initialize: (ctx: Vitest) => Promise<void> | void;
1161
+ /** Called when setting coverage options for Vitest context (`ctx.config.coverage`) */
1162
+ resolveOptions: () => ResolvedCoverageOptions;
1163
+ /** Callback to clean previous reports */
1164
+ clean: (clean?: boolean) => void | Promise<void>;
1165
+ /** Called with coverage results after a single test file has been run */
1166
+ onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void | Promise<void>;
1167
+ /** Callback called when test run fails */
1168
+ onTestFailure?: () => void | Promise<void>;
1169
+ /** Callback to generate final coverage results */
1170
+ generateCoverage: (reportContext: ReportContext) => CoverageResults | Promise<CoverageResults>;
1171
+ /** Callback to convert coverage results to coverage reports. Called with results returned from `generateCoverage` */
1172
+ reportCoverage: (coverage: CoverageResults, reportContext: ReportContext) => void | Promise<void>;
1173
+ /** Callback for `--merge-reports` options. Called with multiple coverage results generated by `generateCoverage`. */
1174
+ mergeReports?: (coverages: CoverageResults[]) => void | Promise<void>;
1175
+ /** Callback called for instrumenting files with coverage counters. */
1176
+ onFileTransform?: (sourceCode: string, id: string, pluginCtx: any) => TransformResult | Promise<TransformResult>;
1177
+ }
1178
+ interface ReportContext {
1179
+ /** Indicates whether all tests were run. False when only specific tests were run. */
1180
+ allTestsRun?: boolean;
1181
+ }
1182
+ interface CoverageProviderModule extends RuntimeCoverageProviderModule {
1183
+ /**
1184
+ * Factory for creating a new coverage provider
1185
+ */
1186
+ getProvider: () => CoverageProvider | Promise<CoverageProvider>;
1187
+ }
1188
+ type CoverageReporter = keyof ReportOptions | (string & {});
1189
+ type CoverageReporterWithOptions<ReporterName extends CoverageReporter = CoverageReporter> = ReporterName extends keyof ReportOptions ? ReportOptions[ReporterName] extends never ? [ReporterName, object] : [ReporterName, Partial<ReportOptions[ReporterName]>] : [ReporterName, Record<string, unknown>];
1190
+ type CoverageProviderName = "v8" | "istanbul" | "custom" | undefined;
1191
+ type CoverageOptions<T extends CoverageProviderName = CoverageProviderName> = T extends "istanbul" ? {
1192
+ provider: T
1193
+ } & CoverageIstanbulOptions : T extends "v8" ? {
1194
+ /**
1195
+ * Provider to use for coverage collection.
1196
+ *
1197
+ * @default 'v8'
1198
+ */
1199
+ provider: T
1200
+ } & CoverageV8Options : T extends "custom" ? {
1201
+ provider: T
1202
+ } & CustomProviderOptions : {
1203
+ provider?: T
1204
+ } & CoverageV8Options;
1205
+ /** Fields that have default values. Internally these will always be defined. */
1206
+ type FieldsWithDefaultValues = "enabled" | "clean" | "cleanOnRerun" | "reportsDirectory" | "exclude" | "extension" | "reportOnFailure" | "allowExternal" | "processingConcurrency";
1207
+ type ResolvedCoverageOptions<T extends CoverageProviderName = CoverageProviderName> = CoverageOptions<T> & Required<Pick<CoverageOptions<T>, FieldsWithDefaultValues>> & {
1208
+ reporter: CoverageReporterWithOptions[]
1209
+ };
1210
+ interface BaseCoverageOptions {
1211
+ /**
1212
+ * Enables coverage collection. Can be overridden using `--coverage` CLI option.
1213
+ *
1214
+ * @default false
1215
+ */
1216
+ enabled?: boolean;
1217
+ /**
1218
+ * List of files included in coverage as glob patterns
1219
+ *
1220
+ * @default ['**']
1221
+ */
1222
+ include?: string[];
1223
+ /**
1224
+ * Extensions for files to be included in coverage
1225
+ *
1226
+ * @default ['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx', '.vue', '.svelte', '.marko']
1227
+ */
1228
+ extension?: string | string[];
1229
+ /**
1230
+ * List of files excluded from coverage as glob patterns
1231
+ *
1232
+ * @default ['coverage/**', 'dist/**', '**\/[.]**', 'packages/*\/test?(s)/**', '**\/*.d.ts', '**\/virtual:*', '**\/__x00__*', '**\/\x00*', 'cypress/**', 'test?(s)/**', 'test?(-*).?(c|m)[jt]s?(x)', '**\/*{.,-}{test,spec}?(-d).?(c|m)[jt]s?(x)', '**\/__tests__/**', '**\/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*', '**\/vitest.{workspace,projects}.[jt]s?(on)', '**\/.{eslint,mocha,prettier}rc.{?(c|m)js,yml}']
1233
+ */
1234
+ exclude?: string[];
1235
+ /**
1236
+ * Whether to include all files, including the untested ones into report
1237
+ *
1238
+ * @default true
1239
+ */
1240
+ all?: boolean;
1241
+ /**
1242
+ * Clean coverage results before running tests
1243
+ *
1244
+ * @default true
1245
+ */
1246
+ clean?: boolean;
1247
+ /**
1248
+ * Clean coverage report on watch rerun
1249
+ *
1250
+ * @default true
1251
+ */
1252
+ cleanOnRerun?: boolean;
1253
+ /**
1254
+ * Directory to write coverage report to
1255
+ *
1256
+ * @default './coverage'
1257
+ */
1258
+ reportsDirectory?: string;
1259
+ /**
1260
+ * Coverage reporters to use.
1261
+ * See [istanbul documentation](https://istanbul.js.org/docs/advanced/alternative-reporters/) for detailed list of all reporters.
1262
+ *
1263
+ * @default ['text', 'html', 'clover', 'json']
1264
+ */
1265
+ reporter?: Arrayable$1<CoverageReporter> | (CoverageReporter | [CoverageReporter] | CoverageReporterWithOptions)[];
1266
+ /**
1267
+ * Do not show files with 100% statement, branch, and function coverage
1268
+ *
1269
+ * @default false
1270
+ */
1271
+ skipFull?: boolean;
1272
+ /**
1273
+ * Configurations for thresholds
1274
+ *
1275
+ * @example
1276
+ *
1277
+ * ```ts
1278
+ * {
1279
+ * // Thresholds for all files
1280
+ * functions: 95,
1281
+ * branches: 70,
1282
+ * perFile: true,
1283
+ * autoUpdate: true,
1284
+ *
1285
+ * // Thresholds for utilities
1286
+ * 'src/utils/**.ts': {
1287
+ * lines: 100,
1288
+ * statements: 95,
1289
+ * }
1290
+ * }
1291
+ * ```
1292
+ */
1293
+ thresholds?: Thresholds | ({
1294
+ [glob: string]: Pick<Thresholds, 100 | "statements" | "functions" | "branches" | "lines">
1295
+ } & Thresholds);
1296
+ /**
1297
+ * Watermarks for statements, lines, branches and functions.
1298
+ *
1299
+ * Default value is `[50,80]` for each property.
1300
+ */
1301
+ watermarks?: {
1302
+ statements?: [number, number]
1303
+ functions?: [number, number]
1304
+ branches?: [number, number]
1305
+ lines?: [number, number]
1306
+ };
1307
+ /**
1308
+ * Generate coverage report even when tests fail.
1309
+ *
1310
+ * @default false
1311
+ */
1312
+ reportOnFailure?: boolean;
1313
+ /**
1314
+ * Collect coverage of files outside the project `root`.
1315
+ *
1316
+ * @default false
1317
+ */
1318
+ allowExternal?: boolean;
1319
+ /**
1320
+ * Apply exclusions again after coverage has been remapped to original sources.
1321
+ * This is useful when your source files are transpiled and may contain source maps
1322
+ * of non-source files.
1323
+ *
1324
+ * Use this option when you are seeing files that show up in report even if they
1325
+ * match your `coverage.exclude` patterns.
1326
+ *
1327
+ * @default false
1328
+ */
1329
+ excludeAfterRemap?: boolean;
1330
+ /**
1331
+ * Concurrency limit used when processing the coverage results.
1332
+ * Defaults to `Math.min(20, os.availableParallelism?.() ?? os.cpus().length)`
1333
+ */
1334
+ processingConcurrency?: number;
1335
+ }
1336
+ interface CoverageIstanbulOptions extends BaseCoverageOptions {
1337
+ /**
1338
+ * Set to array of class method names to ignore for coverage
1339
+ *
1340
+ * @default []
1341
+ */
1342
+ ignoreClassMethods?: string[];
1343
+ }
1344
+ interface CoverageV8Options extends BaseCoverageOptions {
1345
+ /**
1346
+ * Ignore empty lines, comments and other non-runtime code, e.g. Typescript types
1347
+ */
1348
+ ignoreEmptyLines?: boolean;
1349
+ }
1350
+ interface CustomProviderOptions extends Pick<BaseCoverageOptions, FieldsWithDefaultValues> {
1351
+ /** Name of the module or path to a file to load the custom provider from */
1352
+ customProviderModule: string;
1353
+ }
1354
+ interface Thresholds {
1355
+ /** Set global thresholds to `100` */
1356
+ 100?: boolean;
1357
+ /** Check thresholds per file. */
1358
+ perFile?: boolean;
1359
+ /**
1360
+ * Update threshold values automatically when current coverage is higher than earlier thresholds
1361
+ *
1362
+ * @default false
1363
+ */
1364
+ autoUpdate?: boolean;
1365
+ /** Thresholds for statements */
1366
+ statements?: number;
1367
+ /** Thresholds for functions */
1368
+ functions?: number;
1369
+ /** Thresholds for branches */
1370
+ branches?: number;
1371
+ /** Thresholds for lines */
1372
+ lines?: number;
1373
+ }
1374
+
1375
+ type BuiltinEnvironment = "node" | "jsdom" | "happy-dom" | "edge-runtime";
1376
+ type VitestEnvironment = BuiltinEnvironment | (string & Record<never, never>);
1377
+
1378
+ type CSSModuleScopeStrategy = "stable" | "scoped" | "non-scoped";
1379
+ type ApiConfig = Pick<ServerOptions, "port" | "strictPort" | "host" | "middlewareMode">;
1380
+
1381
+ type VitestRunMode = "test" | "benchmark";
1382
+ interface SequenceOptions {
1383
+ /**
1384
+ * Class that handles sorting and sharding algorithm.
1385
+ * If you only need to change sorting, you can extend
1386
+ * your custom sequencer from `BaseSequencer` from `vitest/node`.
1387
+ * @default BaseSequencer
1388
+ */
1389
+ sequencer?: TestSequencerConstructor;
1390
+ /**
1391
+ * Should files and tests run in random order.
1392
+ * @default false
1393
+ */
1394
+ shuffle?: boolean | {
1395
+ /**
1396
+ * Should files run in random order. Long running tests will not start
1397
+ * earlier if you enable this option.
1398
+ * @default false
1399
+ */
1400
+ files?: boolean
1401
+ /**
1402
+ * Should tests run in random order.
1403
+ * @default false
1404
+ */
1405
+ tests?: boolean
1406
+ };
1407
+ /**
1408
+ * Should tests run in parallel.
1409
+ * @default false
1410
+ */
1411
+ concurrent?: boolean;
1412
+ /**
1413
+ * Defines how setup files should be ordered
1414
+ * - 'parallel' will run all setup files in parallel
1415
+ * - 'list' will run all setup files in the order they are defined in the config file
1416
+ * @default 'parallel'
1417
+ */
1418
+ setupFiles?: SequenceSetupFiles;
1419
+ /**
1420
+ * Seed for the random number generator.
1421
+ * @default Date.now()
1422
+ */
1423
+ seed?: number;
1424
+ /**
1425
+ * Defines how hooks should be ordered
1426
+ * - `stack` will order "after" hooks in reverse order, "before" hooks will run sequentially
1427
+ * - `list` will order hooks in the order they are defined
1428
+ * - `parallel` will run hooks in a single group in parallel
1429
+ * @default 'stack'
1430
+ */
1431
+ hooks?: SequenceHooks;
1432
+ }
1433
+ type DepsOptimizationOptions = Omit<DepOptimizationConfig, "disabled" | "noDiscovery"> & {
1434
+ enabled?: boolean
1435
+ };
1436
+ interface TransformModePatterns {
1437
+ /**
1438
+ * Use SSR transform pipeline for all modules inside specified tests.
1439
+ * Vite plugins will receive `ssr: true` flag when processing those files.
1440
+ *
1441
+ * @default tests with node or edge environment
1442
+ */
1443
+ ssr?: string[];
1444
+ /**
1445
+ * First do a normal transform pipeline (targeting browser),
1446
+ * then then do a SSR rewrite to run the code in Node.
1447
+ * Vite plugins will receive `ssr: false` flag when processing those files.
1448
+ *
1449
+ * @default tests with jsdom or happy-dom environment
1450
+ */
1451
+ web?: string[];
1452
+ }
1453
+ interface DepsOptions {
1454
+ /**
1455
+ * Enable dependency optimization. This can improve the performance of your tests.
1456
+ */
1457
+ optimizer?: {
1458
+ web?: DepsOptimizationOptions
1459
+ ssr?: DepsOptimizationOptions
1460
+ };
1461
+ web?: {
1462
+ /**
1463
+ * Should Vitest process assets (.png, .svg, .jpg, etc) files and resolve them like Vite does in the browser.
1464
+ *
1465
+ * These module will have a default export equal to the path to the asset, if no query is specified.
1466
+ *
1467
+ * **At the moment, this option only works with `{ pool: 'vmThreads' }`.**
1468
+ *
1469
+ * @default true
1470
+ */
1471
+ transformAssets?: boolean
1472
+ /**
1473
+ * Should Vitest process CSS (.css, .scss, .sass, etc) files and resolve them like Vite does in the browser.
1474
+ *
1475
+ * If CSS files are disabled with `css` options, this option will just silence UNKNOWN_EXTENSION errors.
1476
+ *
1477
+ * **At the moment, this option only works with `{ pool: 'vmThreads' }`.**
1478
+ *
1479
+ * @default true
1480
+ */
1481
+ transformCss?: boolean
1482
+ /**
1483
+ * Regexp pattern to match external files that should be transformed.
1484
+ *
1485
+ * By default, files inside `node_modules` are externalized and not transformed.
1486
+ *
1487
+ * **At the moment, this option only works with `{ pool: 'vmThreads' }`.**
1488
+ *
1489
+ * @default []
1490
+ */
1491
+ transformGlobPattern?: RegExp | RegExp[]
1492
+ };
1493
+ /**
1494
+ * Externalize means that Vite will bypass the package to native Node.
1495
+ *
1496
+ * Externalized dependencies will not be applied Vite's transformers and resolvers.
1497
+ * And does not support HMR on reload.
1498
+ *
1499
+ * Typically, packages under `node_modules` are externalized.
1500
+ *
1501
+ * @deprecated If you rely on vite-node directly, use `server.deps.external` instead. Otherwise, consider using `deps.optimizer.{web,ssr}.exclude`.
1502
+ */
1503
+ external?: (string | RegExp)[];
1504
+ /**
1505
+ * Vite will process inlined modules.
1506
+ *
1507
+ * This could be helpful to handle packages that ship `.js` in ESM format (that Node can't handle).
1508
+ *
1509
+ * If `true`, every dependency will be inlined
1510
+ *
1511
+ * @deprecated If you rely on vite-node directly, use `server.deps.inline` instead. Otherwise, consider using `deps.optimizer.{web,ssr}.include`.
1512
+ */
1513
+ inline?: (string | RegExp)[] | true;
1514
+ /**
1515
+ * Interpret CJS module's default as named exports
1516
+ *
1517
+ * @default true
1518
+ */
1519
+ interopDefault?: boolean;
1520
+ /**
1521
+ * When a dependency is a valid ESM package, try to guess the cjs version based on the path.
1522
+ * This will significantly improve the performance in huge repo, but might potentially
1523
+ * cause some misalignment if a package have different logic in ESM and CJS mode.
1524
+ *
1525
+ * @default false
1526
+ *
1527
+ * @deprecated Use `server.deps.fallbackCJS` instead.
1528
+ */
1529
+ fallbackCJS?: boolean;
1530
+ /**
1531
+ * A list of directories relative to the config file that should be treated as module directories.
1532
+ *
1533
+ * @default ['node_modules']
1534
+ */
1535
+ moduleDirectories?: string[];
1536
+ }
1537
+ type InlineReporter = Reporter;
1538
+ type ReporterName = BuiltinReporters | "html" | (string & {});
1539
+ type ReporterWithOptions<Name extends ReporterName = ReporterName> = Name extends keyof BuiltinReporterOptions ? BuiltinReporterOptions[Name] extends never ? [Name, object] : [Name, Partial<BuiltinReporterOptions[Name]>] : [Name, Record<string, unknown>];
1540
+ interface ResolveSnapshotPathHandlerContext {
1541
+ config: SerializedConfig;
1542
+ }
1543
+ type ResolveSnapshotPathHandler = (testPath: string, snapExtension: string, context: ResolveSnapshotPathHandlerContext) => string;
1544
+ interface InlineConfig {
1545
+ /**
1546
+ * Name of the project. Will be used to display in the reporter.
1547
+ */
1548
+ name?: string;
1549
+ /**
1550
+ * Benchmark options.
1551
+ *
1552
+ * @default {}
1553
+ */
1554
+ benchmark?: BenchmarkUserOptions;
1555
+ /**
1556
+ * Include globs for test files
1557
+ *
1558
+ * @default ['**\/*.{test,spec}.?(c|m)[jt]s?(x)']
1559
+ */
1560
+ include?: string[];
1561
+ /**
1562
+ * Exclude globs for test files
1563
+ * @default ['**\/node_modules/**', '**\/dist/**', '**\/cypress/**', '**\/.{idea,git,cache,output,temp}/**', '**\/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*']
1564
+ */
1565
+ exclude?: string[];
1566
+ /**
1567
+ * Include globs for in-source test files
1568
+ *
1569
+ * @default []
1570
+ */
1571
+ includeSource?: string[];
1572
+ /**
1573
+ * Handling for dependencies inlining or externalizing
1574
+ *
1575
+ */
1576
+ deps?: DepsOptions;
1577
+ /**
1578
+ * Vite-node server options
1579
+ */
1580
+ server?: Omit<ViteNodeServerOptions, "transformMode">;
1581
+ /**
1582
+ * Base directory to scan for the test files
1583
+ *
1584
+ * @default `config.root`
1585
+ */
1586
+ dir?: string;
1587
+ /**
1588
+ * Register apis globally
1589
+ *
1590
+ * @default false
1591
+ */
1592
+ globals?: boolean;
1593
+ /**
1594
+ * Running environment
1595
+ *
1596
+ * Supports 'node', 'jsdom', 'happy-dom', 'edge-runtime'
1597
+ *
1598
+ * If used unsupported string, will try to load the package `vitest-environment-${env}`
1599
+ *
1600
+ * @default 'node'
1601
+ */
1602
+ environment?: VitestEnvironment;
1603
+ /**
1604
+ * Environment options.
1605
+ */
1606
+ environmentOptions?: EnvironmentOptions;
1607
+ /**
1608
+ * Automatically assign environment based on globs. The first match will be used.
1609
+ * This has effect only when running tests inside Node.js.
1610
+ *
1611
+ * Format: [glob, environment-name]
1612
+ *
1613
+ * @deprecated use [`workspace`](https://vitest.dev/config/#environmentmatchglobs) instead
1614
+ * @default []
1615
+ * @example [
1616
+ * // all tests in tests/dom will run in jsdom
1617
+ * ['tests/dom/**', 'jsdom'],
1618
+ * // all tests in tests/ with .edge.test.ts will run in edge-runtime
1619
+ * ['**\/*.edge.test.ts', 'edge-runtime'],
1620
+ * // ...
1621
+ * ]
1622
+ */
1623
+ environmentMatchGlobs?: [string, VitestEnvironment][];
1624
+ /**
1625
+ * Run tests in an isolated environment. This option has no effect on vmThreads pool.
1626
+ *
1627
+ * Disabling this option might improve performance if your code doesn't rely on side effects.
1628
+ *
1629
+ * @default true
1630
+ */
1631
+ isolate?: boolean;
1632
+ /**
1633
+ * Pool used to run tests in.
1634
+ *
1635
+ * Supports 'threads', 'forks', 'vmThreads'
1636
+ *
1637
+ * @default 'forks'
1638
+ */
1639
+ pool?: Exclude<Pool, "browser">;
1640
+ /**
1641
+ * Pool options
1642
+ */
1643
+ poolOptions?: PoolOptions;
1644
+ /**
1645
+ * Maximum number or percentage of workers to run tests in. `poolOptions.{threads,vmThreads}.maxThreads`/`poolOptions.forks.maxForks` has higher priority.
1646
+ */
1647
+ maxWorkers?: number | string;
1648
+ /**
1649
+ * Minimum number or percentage of workers to run tests in. `poolOptions.{threads,vmThreads}.minThreads`/`poolOptions.forks.minForks` has higher priority.
1650
+ */
1651
+ minWorkers?: number | string;
1652
+ /**
1653
+ * Should all test files run in parallel. Doesn't affect tests running in the same file.
1654
+ * Setting this to `false` will override `maxWorkers` and `minWorkers` options to `1`.
1655
+ *
1656
+ * @default true
1657
+ */
1658
+ fileParallelism?: boolean;
1659
+ /**
1660
+ * Automatically assign pool based on globs. The first match will be used.
1661
+ *
1662
+ * Format: [glob, pool-name]
1663
+ *
1664
+ * @deprecated use [`workspace`](https://vitest.dev/config/#poolmatchglobs) instead
1665
+ * @default []
1666
+ * @example [
1667
+ * // all tests in "forks" directory will run using "poolOptions.forks" API
1668
+ * ['tests/forks/**', 'forks'],
1669
+ * // all other tests will run based on "poolOptions.threads" option, if you didn't specify other globs
1670
+ * // ...
1671
+ * ]
1672
+ */
1673
+ poolMatchGlobs?: [string, Exclude<Pool, "browser">][];
1674
+ /**
1675
+ * Path to a workspace configuration file
1676
+ */
1677
+ workspace?: string | TestProjectConfiguration[];
1678
+ /**
1679
+ * Update snapshot
1680
+ *
1681
+ * @default false
1682
+ */
1683
+ update?: boolean;
1684
+ /**
1685
+ * Watch mode
1686
+ *
1687
+ * @default !process.env.CI
1688
+ */
1689
+ watch?: boolean;
1690
+ /**
1691
+ * Project root
1692
+ *
1693
+ * @default process.cwd()
1694
+ */
1695
+ root?: string;
1696
+ /**
1697
+ * Custom reporter for output. Can contain one or more built-in report names, reporter instances,
1698
+ * and/or paths to custom reporters.
1699
+ *
1700
+ * @default []
1701
+ */
1702
+ reporters?: Arrayable$1<ReporterName | InlineReporter> | ((ReporterName | InlineReporter) | [ReporterName] | ReporterWithOptions)[];
1703
+ /**
1704
+ * Write test results to a file when the --reporter=json` or `--reporter=junit` option is also specified.
1705
+ * Also definable individually per reporter by using an object instead.
1706
+ */
1707
+ outputFile?: string | (Partial<Record<BuiltinReporters, string>> & Record<string, string>);
1708
+ /**
1709
+ * Default timeout of a test in milliseconds
1710
+ *
1711
+ * @default 5000
1712
+ */
1713
+ testTimeout?: number;
1714
+ /**
1715
+ * Default timeout of a hook in milliseconds
1716
+ *
1717
+ * @default 10000
1718
+ */
1719
+ hookTimeout?: number;
1720
+ /**
1721
+ * Default timeout to wait for close when Vitest shuts down, in milliseconds
1722
+ *
1723
+ * @default 10000
1724
+ */
1725
+ teardownTimeout?: number;
1726
+ /**
1727
+ * Silent mode
1728
+ *
1729
+ * @default false
1730
+ */
1731
+ silent?: boolean;
1732
+ /**
1733
+ * Hide logs for skipped tests
1734
+ *
1735
+ * @default false
1736
+ */
1737
+ hideSkippedTests?: boolean;
1738
+ /**
1739
+ * Path to setup files
1740
+ */
1741
+ setupFiles?: string | string[];
1742
+ /**
1743
+ * Path to global setup files
1744
+ */
1745
+ globalSetup?: string | string[];
1746
+ /**
1747
+ * Glob patter of file paths that will trigger the whole suite rerun
1748
+ *
1749
+ * Useful if you are testing calling CLI commands
1750
+ *
1751
+ * @default ['**\/package.json/**', '**\/{vitest,vite}.config.*\/**']
1752
+ */
1753
+ forceRerunTriggers?: string[];
1754
+ /**
1755
+ * Coverage options
1756
+ */
1757
+ coverage?: CoverageOptions;
1758
+ /**
1759
+ * run test names with the specified pattern
1760
+ */
1761
+ testNamePattern?: string | RegExp;
1762
+ /**
1763
+ * Will call `.mockClear()` on all spies before each test
1764
+ * @default false
1765
+ */
1766
+ clearMocks?: boolean;
1767
+ /**
1768
+ * Will call `.mockReset()` on all spies before each test
1769
+ * @default false
1770
+ */
1771
+ mockReset?: boolean;
1772
+ /**
1773
+ * Will call `.mockRestore()` on all spies before each test
1774
+ * @default false
1775
+ */
1776
+ restoreMocks?: boolean;
1777
+ /**
1778
+ * Will restore all global stubs to their original values before each test
1779
+ * @default false
1780
+ */
1781
+ unstubGlobals?: boolean;
1782
+ /**
1783
+ * Will restore all env stubs to their original values before each test
1784
+ * @default false
1785
+ */
1786
+ unstubEnvs?: boolean;
1787
+ /**
1788
+ * Serve API options.
1789
+ *
1790
+ * When set to true, the default port is 51204.
1791
+ *
1792
+ * @default false
1793
+ */
1794
+ api?: boolean | number | ApiConfig;
1795
+ /**
1796
+ * Enable Vitest UI
1797
+ *
1798
+ * @default false
1799
+ */
1800
+ ui?: boolean;
1801
+ /**
1802
+ * options for test in a browser environment
1803
+ * @experimental
1804
+ *
1805
+ * @default false
1806
+ */
1807
+ browser?: BrowserConfigOptions;
1808
+ /**
1809
+ * Open UI automatically.
1810
+ *
1811
+ * @default !process.env.CI
1812
+ */
1813
+ open?: boolean;
1814
+ /**
1815
+ * Base url for the UI
1816
+ *
1817
+ * @default '/__vitest__/'
1818
+ */
1819
+ uiBase?: string;
1820
+ /**
1821
+ * Determine the transform method for all modules imported inside a test that matches the glob pattern.
1822
+ */
1823
+ testTransformMode?: TransformModePatterns;
1824
+ /**
1825
+ * Format options for snapshot testing.
1826
+ */
1827
+ snapshotFormat?: Omit<PrettyFormatOptions, "plugins">;
1828
+ /**
1829
+ * Path to a module which has a default export of diff config.
1830
+ */
1831
+ diff?: string | SerializedDiffOptions;
1832
+ /**
1833
+ * Paths to snapshot serializer modules.
1834
+ */
1835
+ snapshotSerializers?: string[];
1836
+ /**
1837
+ * Resolve custom snapshot path
1838
+ */
1839
+ resolveSnapshotPath?: ResolveSnapshotPathHandler;
1840
+ /**
1841
+ * Path to a custom snapshot environment module that has a default export of `SnapshotEnvironment` object.
1842
+ */
1843
+ snapshotEnvironment?: string;
1844
+ /**
1845
+ * Pass with no tests
1846
+ */
1847
+ passWithNoTests?: boolean;
1848
+ /**
1849
+ * Allow tests and suites that are marked as only
1850
+ *
1851
+ * @default !process.env.CI
1852
+ */
1853
+ allowOnly?: boolean;
1854
+ /**
1855
+ * Show heap usage after each test. Useful for debugging memory leaks.
1856
+ */
1857
+ logHeapUsage?: boolean;
1858
+ /**
1859
+ * Custom environment variables assigned to `process.env` before running tests.
1860
+ */
1861
+ env?: Partial<NodeJS.ProcessEnv>;
1862
+ /**
1863
+ * Options for @sinon/fake-timers
1864
+ */
1865
+ fakeTimers?: FakeTimerInstallOpts;
1866
+ /**
1867
+ * Custom handler for console.log in tests.
1868
+ *
1869
+ * Return `false` to ignore the log.
1870
+ */
1871
+ onConsoleLog?: (log: string, type: "stdout" | "stderr") => boolean | void;
1872
+ /**
1873
+ * Enable stack trace filtering. If absent, all stack trace frames
1874
+ * will be shown.
1875
+ *
1876
+ * Return `false` to omit the frame.
1877
+ */
1878
+ onStackTrace?: (error: ErrorWithDiff, frame: ParsedStack) => boolean | void;
1879
+ /**
1880
+ * Indicates if CSS files should be processed.
1881
+ *
1882
+ * When excluded, the CSS files will be replaced with empty strings to bypass the subsequent processing.
1883
+ *
1884
+ * @default { include: [], modules: { classNameStrategy: false } }
1885
+ */
1886
+ css?: boolean | {
1887
+ include?: RegExp | RegExp[]
1888
+ exclude?: RegExp | RegExp[]
1889
+ modules?: {
1890
+ classNameStrategy?: CSSModuleScopeStrategy
1891
+ }
1892
+ };
1893
+ /**
1894
+ * A number of tests that are allowed to run at the same time marked with `test.concurrent`.
1895
+ * @default 5
1896
+ */
1897
+ maxConcurrency?: number;
1898
+ /**
1899
+ * Options for configuring cache policy.
1900
+ * @default { dir: 'node_modules/.vite/vitest' }
1901
+ */
1902
+ cache?: false | {
1903
+ /**
1904
+ * @deprecated Use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest".
1905
+ */
1906
+ dir: string
1907
+ };
1908
+ /**
1909
+ * Options for configuring the order of running tests.
1910
+ */
1911
+ sequence?: SequenceOptions;
1912
+ /**
1913
+ * Specifies an `Object`, or an `Array` of `Object`,
1914
+ * which defines aliases used to replace values in `import` or `require` statements.
1915
+ * Will be merged with the default aliases inside `resolve.alias`.
1916
+ */
1917
+ alias?: AliasOptions;
1918
+ /**
1919
+ * Ignore any unhandled errors that occur
1920
+ *
1921
+ * @default false
1922
+ */
1923
+ dangerouslyIgnoreUnhandledErrors?: boolean;
1924
+ /**
1925
+ * Options for configuring typechecking test environment.
1926
+ */
1927
+ typecheck?: Partial<TypecheckConfig>;
1928
+ /**
1929
+ * The number of milliseconds after which a test is considered slow and reported as such in the results.
1930
+ *
1931
+ * @default 300
1932
+ */
1933
+ slowTestThreshold?: number;
1934
+ /**
1935
+ * Path to a custom test runner.
1936
+ */
1937
+ runner?: string;
1938
+ /**
1939
+ * Debug tests by opening `node:inspector` in worker / child process.
1940
+ * Provides similar experience as `--inspect` Node CLI argument.
1941
+ *
1942
+ * Requires `poolOptions.threads.singleThread: true` OR `poolOptions.forks.singleFork: true`.
1943
+ */
1944
+ inspect?: boolean | string;
1945
+ /**
1946
+ * Debug tests by opening `node:inspector` in worker / child process and wait for debugger to connect.
1947
+ * Provides similar experience as `--inspect-brk` Node CLI argument.
1948
+ *
1949
+ * Requires `poolOptions.threads.singleThread: true` OR `poolOptions.forks.singleFork: true`.
1950
+ */
1951
+ inspectBrk?: boolean | string;
1952
+ /**
1953
+ * Inspector options. If `--inspect` or `--inspect-brk` is enabled, these options will be passed to the inspector.
1954
+ */
1955
+ inspector?: {
1956
+ /**
1957
+ * Enable inspector
1958
+ */
1959
+ enabled?: boolean
1960
+ /**
1961
+ * Port to run inspector on
1962
+ */
1963
+ port?: number
1964
+ /**
1965
+ * Host to run inspector on
1966
+ */
1967
+ host?: string
1968
+ /**
1969
+ * Wait for debugger to connect before running tests
1970
+ */
1971
+ waitForDebugger?: boolean
1972
+ };
1973
+ /**
1974
+ * Define variables that will be returned from `inject` in the test environment.
1975
+ * @example
1976
+ * ```ts
1977
+ * // vitest.config.ts
1978
+ * export default defineConfig({
1979
+ * test: {
1980
+ * provide: {
1981
+ * someKey: 'someValue'
1982
+ * }
1983
+ * }
1984
+ * })
1985
+ * ```
1986
+ * ```ts
1987
+ * // test file
1988
+ * import { inject } from 'vitest'
1989
+ * const value = inject('someKey') // 'someValue'
1990
+ * ```
1991
+ */
1992
+ provide?: Partial<ProvidedContext>;
1993
+ /**
1994
+ * Configuration options for expect() matches.
1995
+ */
1996
+ expect?: {
1997
+ /**
1998
+ * Throw an error if tests don't have any expect() assertions.
1999
+ */
2000
+ requireAssertions?: boolean
2001
+ /**
2002
+ * Default options for expect.poll()
2003
+ */
2004
+ poll?: {
2005
+ /**
2006
+ * Timeout in milliseconds
2007
+ * @default 1000
2008
+ */
2009
+ timeout?: number
2010
+ /**
2011
+ * Polling interval in milliseconds
2012
+ * @default 50
2013
+ */
2014
+ interval?: number
2015
+ }
2016
+ };
2017
+ /**
2018
+ * Modify default Chai config. Vitest uses Chai for `expect` and `assert` matches.
2019
+ * https://github.com/chaijs/chai/blob/4.x.x/lib/chai/config.js
2020
+ */
2021
+ chaiConfig?: ChaiConfig;
2022
+ /**
2023
+ * Stop test execution when given number of tests have failed.
2024
+ */
2025
+ bail?: number;
2026
+ /**
2027
+ * Retry the test specific number of times if it fails.
2028
+ *
2029
+ * @default 0
2030
+ */
2031
+ retry?: number;
2032
+ /**
2033
+ * Show full diff when snapshot fails instead of a patch.
2034
+ */
2035
+ expandSnapshotDiff?: boolean;
2036
+ /**
2037
+ * By default, Vitest automatically intercepts console logging during tests for extra formatting of test file, test title, etc...
2038
+ * This is also required for console log preview on Vitest UI.
2039
+ * However, disabling such interception might help when you want to debug a code with normal synchronous terminal console logging.
2040
+ *
2041
+ * This option has no effect on browser pool since Vitest preserves original logging on browser devtools.
2042
+ *
2043
+ * @default false
2044
+ */
2045
+ disableConsoleIntercept?: boolean;
2046
+ /**
2047
+ * Always print console stack traces.
2048
+ *
2049
+ * @default false
2050
+ */
2051
+ printConsoleTrace?: boolean;
2052
+ /**
2053
+ * Include "location" property inside the test definition
2054
+ *
2055
+ * @default false
2056
+ */
2057
+ includeTaskLocation?: boolean;
2058
+ }
2059
+ interface TypecheckConfig {
2060
+ /**
2061
+ * Run typechecking tests alongside regular tests.
2062
+ */
2063
+ enabled?: boolean;
2064
+ /**
2065
+ * When typechecking is enabled, only run typechecking tests.
2066
+ */
2067
+ only?: boolean;
2068
+ /**
2069
+ * What tools to use for type checking.
2070
+ *
2071
+ * @default 'tsc'
2072
+ */
2073
+ checker: "tsc" | "vue-tsc" | (string & Record<never, never>);
2074
+ /**
2075
+ * Pattern for files that should be treated as test files
2076
+ *
2077
+ * @default ['**\/*.{test,spec}-d.?(c|m)[jt]s?(x)']
2078
+ */
2079
+ include: string[];
2080
+ /**
2081
+ * Pattern for files that should not be treated as test files
2082
+ *
2083
+ * @default ['**\/node_modules/**', '**\/dist/**', '**\/cypress/**', '**\/.{idea,git,cache,output,temp}/**', '**\/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*']
2084
+ */
2085
+ exclude: string[];
2086
+ /**
2087
+ * Check JS files that have `@ts-check` comment.
2088
+ * If you have it enabled in tsconfig, this will not overwrite it.
2089
+ */
2090
+ allowJs?: boolean;
2091
+ /**
2092
+ * Do not fail, if Vitest found errors outside the test files.
2093
+ */
2094
+ ignoreSourceErrors?: boolean;
2095
+ /**
2096
+ * Path to tsconfig, relative to the project root.
2097
+ */
2098
+ tsconfig?: string;
2099
+ }
2100
+ interface UserConfig extends InlineConfig {
2101
+ /**
2102
+ * Path to the config file.
2103
+ *
2104
+ * Default resolving to `vitest.config.*`, `vite.config.*`
2105
+ *
2106
+ * Setting to `false` will disable config resolving.
2107
+ */
2108
+ config?: string | false | undefined;
2109
+ /**
2110
+ * Do not run tests when Vitest starts.
2111
+ *
2112
+ * Vitest will only run tests if it's called programmatically or the test file changes.
2113
+ *
2114
+ * CLI file filters will be ignored.
2115
+ */
2116
+ standalone?: boolean;
2117
+ /**
2118
+ * Use happy-dom
2119
+ */
2120
+ dom?: boolean;
2121
+ /**
2122
+ * Run tests that cover a list of source files
2123
+ */
2124
+ related?: string[] | string;
2125
+ /**
2126
+ * Overrides Vite mode
2127
+ * @default 'test'
2128
+ */
2129
+ mode?: string;
2130
+ /**
2131
+ * Runs tests that are affected by the changes in the repository, or between specified branch or commit hash
2132
+ * Requires initialized git repository
2133
+ * @default false
2134
+ */
2135
+ changed?: boolean | string;
2136
+ /**
2137
+ * Test suite shard to execute in a format of <index>/<count>.
2138
+ * Will divide tests into a `count` numbers, and run only the `indexed` part.
2139
+ * Cannot be used with enabled watch.
2140
+ * @example --shard=2/3
2141
+ */
2142
+ shard?: string;
2143
+ /**
2144
+ * Name of the project or projects to run.
2145
+ */
2146
+ project?: string | string[];
2147
+ /**
2148
+ * Additional exclude patterns
2149
+ */
2150
+ cliExclude?: string[];
2151
+ /**
2152
+ * Override vite config's clearScreen from cli
2153
+ */
2154
+ clearScreen?: boolean;
2155
+ /**
2156
+ * benchmark.compare option exposed at the top level for cli
2157
+ */
2158
+ compare?: string;
2159
+ /**
2160
+ * benchmark.outputJson option exposed at the top level for cli
2161
+ */
2162
+ outputJson?: string;
2163
+ /**
2164
+ * Directory of blob reports to merge
2165
+ * @default '.vitest-reports'
2166
+ */
2167
+ mergeReports?: string;
2168
+ }
2169
+ interface ResolvedConfig extends Omit<Required<UserConfig>, "project" | "config" | "filters" | "browser" | "coverage" | "testNamePattern" | "related" | "api" | "reporters" | "resolveSnapshotPath" | "benchmark" | "shard" | "cache" | "sequence" | "typecheck" | "runner" | "poolOptions" | "pool" | "cliExclude" | "diff" | "setupFiles" | "snapshotEnvironment" | "bail"> {
2170
+ mode: VitestRunMode;
2171
+ base?: string;
2172
+ diff?: string | SerializedDiffOptions;
2173
+ bail?: number;
2174
+ setupFiles: string[];
2175
+ snapshotEnvironment?: string;
2176
+ config?: string;
2177
+ filters?: string[];
2178
+ testNamePattern?: RegExp;
2179
+ related?: string[];
2180
+ coverage: ResolvedCoverageOptions;
2181
+ snapshotOptions: SnapshotStateOptions;
2182
+ browser: ResolvedBrowserOptions;
2183
+ pool: Pool;
2184
+ poolOptions?: ResolvedPoolOptions;
2185
+ reporters: (InlineReporter | ReporterWithOptions)[];
2186
+ defines: Record<string, any>;
2187
+ api: ApiConfig & {
2188
+ token: string
2189
+ };
2190
+ cliExclude?: string[];
2191
+ project: string[];
2192
+ benchmark?: Required<Omit<BenchmarkUserOptions, "outputFile" | "compare" | "outputJson">> & Pick<BenchmarkUserOptions, "outputFile" | "compare" | "outputJson">;
2193
+ shard?: {
2194
+ index: number
2195
+ count: number
2196
+ };
2197
+ cache: {
2198
+ /**
2199
+ * @deprecated
2200
+ */
2201
+ dir: string
2202
+ } | false;
2203
+ sequence: {
2204
+ sequencer: TestSequencerConstructor
2205
+ hooks: SequenceHooks
2206
+ setupFiles: SequenceSetupFiles
2207
+ shuffle?: boolean
2208
+ concurrent?: boolean
2209
+ seed: number
2210
+ };
2211
+ typecheck: Omit<TypecheckConfig, "enabled"> & {
2212
+ enabled: boolean
2213
+ };
2214
+ runner?: string;
2215
+ maxWorkers: number;
2216
+ minWorkers: number;
2217
+ }
2218
+ type NonProjectOptions = "shard" | "watch" | "run" | "cache" | "update" | "reporters" | "outputFile" | "teardownTimeout" | "silent" | "forceRerunTriggers" | "testNamePattern" | "ui" | "open" | "uiBase" | "snapshotFormat" | "resolveSnapshotPath" | "passWithNoTests" | "onConsoleLog" | "onStackTrace" | "dangerouslyIgnoreUnhandledErrors" | "slowTestThreshold" | "inspect" | "inspectBrk" | "coverage" | "maxWorkers" | "minWorkers" | "fileParallelism" | "workspace";
2219
+ type ProjectConfig = Omit<InlineConfig, NonProjectOptions | "sequencer" | "deps" | "poolOptions"> & {
2220
+ mode?: string
2221
+ sequencer?: Omit<SequenceOptions, "sequencer" | "seed">
2222
+ deps?: Omit<DepsOptions, "moduleDirectories">
2223
+ poolOptions?: {
2224
+ threads?: Pick<NonNullable<PoolOptions["threads"]>, "singleThread" | "isolate">
2225
+ vmThreads?: Pick<NonNullable<PoolOptions["vmThreads"]>, "singleThread">
2226
+ forks?: Pick<NonNullable<PoolOptions["forks"]>, "singleFork" | "isolate">
2227
+ }
2228
+ };
2229
+ type ResolvedProjectConfig = Omit<ResolvedConfig, Exclude<NonProjectOptions, "coverage" | "watch">>;
2230
+ interface UserWorkspaceConfig extends UserConfig$1 {
2231
+ test?: ProjectConfig;
2232
+ }
2233
+ type UserProjectConfigFn = (env: ConfigEnv) => UserWorkspaceConfig | Promise<UserWorkspaceConfig>;
2234
+ type UserProjectConfigExport = UserWorkspaceConfig | Promise<UserWorkspaceConfig> | UserProjectConfigFn;
2235
+ type TestProjectConfiguration = string | (UserProjectConfigExport & {
2236
+ /**
2237
+ * Relative path to the extendable config. All other options will be merged with this config.
2238
+ * If `true`, the project will inherit all options from the root config.
2239
+ * @example '../vite.config.ts'
2240
+ */
2241
+ extends?: string | true
2242
+ });
2243
+ /** @deprecated use `TestProjectConfiguration` instead */
2244
+ type WorkspaceProjectConfiguration = TestProjectConfiguration;
2245
+
2246
+ interface BrowserProviderInitializationOptions {
2247
+ browser: string;
2248
+ options?: BrowserProviderOptions;
2249
+ }
2250
+ interface CDPSession {
2251
+ send: (method: string, params?: Record<string, unknown>) => Promise<unknown>;
2252
+ on: (event: string, listener: (...args: unknown[]) => void) => void;
2253
+ once: (event: string, listener: (...args: unknown[]) => void) => void;
2254
+ off: (event: string, listener: (...args: unknown[]) => void) => void;
2255
+ }
2256
+ interface BrowserProvider {
2257
+ name: string;
2258
+ /**
2259
+ * @experimental opt-in into file parallelisation
2260
+ */
2261
+ supportsParallelism: boolean;
2262
+ getSupportedBrowsers: () => readonly string[];
2263
+ getCommandsContext: (sessionId: string) => Record<string, unknown>;
2264
+ openPage: (sessionId: string, url: string, beforeNavigate?: () => Promise<void>) => Promise<void>;
2265
+ getCDPSession?: (sessionId: string) => Promise<CDPSession>;
2266
+ close: () => Awaitable$1<void>;
2267
+ initialize(ctx: TestProject, options: BrowserProviderInitializationOptions): Awaitable$1<void>;
2268
+ }
2269
+ interface BrowserProviderModule {
2270
+ new (): BrowserProvider;
2271
+ }
2272
+ interface BrowserProviderOptions {}
2273
+ type BrowserBuiltinProvider = "webdriverio" | "playwright" | "preview";
2274
+ type UnsupportedProperties = "browser" | "typecheck" | "alias" | "sequence" | "root" | "pool" | "poolOptions" | "runner" | "api" | "deps" | "testTransformMode" | "poolMatchGlobs" | "environmentMatchGlobs" | "environment" | "environmentOptions" | "server" | "benchmark";
2275
+ interface BrowserInstanceOption extends BrowserProviderOptions, Omit<ProjectConfig, UnsupportedProperties>, Pick<BrowserConfigOptions, "headless" | "locators" | "viewport" | "testerHtmlPath" | "screenshotDirectory" | "screenshotFailures"> {
2276
+ /**
2277
+ * Name of the browser
2278
+ */
2279
+ browser: string;
2280
+ }
2281
+ interface BrowserConfigOptions {
2282
+ /**
2283
+ * if running tests in the browser should be the default
2284
+ *
2285
+ * @default false
2286
+ */
2287
+ enabled?: boolean;
2288
+ /**
2289
+ * Name of the browser
2290
+ * @deprecated use `instances` instead. if both are defined, this will filter `instances` by name.
2291
+ */
2292
+ name?: string;
2293
+ /**
2294
+ * Configurations for different browser setups
2295
+ */
2296
+ instances?: BrowserInstanceOption[];
2297
+ /**
2298
+ * Browser provider
2299
+ *
2300
+ * @default 'preview'
2301
+ */
2302
+ provider?: BrowserBuiltinProvider | (string & {});
2303
+ /**
2304
+ * Options that are passed down to a browser provider.
2305
+ * To support type hinting, add one of the types to your tsconfig.json "compilerOptions.types" field:
2306
+ *
2307
+ * - for webdriverio: `@vitest/browser/providers/webdriverio`
2308
+ * - for playwright: `@vitest/browser/providers/playwright`
2309
+ *
2310
+ * @example
2311
+ * { playwright: { launch: { devtools: true } }
2312
+ * @deprecated use `instances` instead
2313
+ */
2314
+ providerOptions?: BrowserProviderOptions;
2315
+ /**
2316
+ * enable headless mode
2317
+ *
2318
+ * @default process.env.CI
2319
+ */
2320
+ headless?: boolean;
2321
+ /**
2322
+ * Serve API options.
2323
+ *
2324
+ * The default port is 63315.
2325
+ */
2326
+ api?: ApiConfig | number;
2327
+ /**
2328
+ * Isolate test environment after each test
2329
+ *
2330
+ * @default true
2331
+ */
2332
+ isolate?: boolean;
2333
+ /**
2334
+ * Run test files in parallel if provider supports this option
2335
+ * This option only has effect in headless mode (enabled in CI by default)
2336
+ *
2337
+ * @default // Same as "test.fileParallelism"
2338
+ */
2339
+ fileParallelism?: boolean;
2340
+ /**
2341
+ * Show Vitest UI
2342
+ *
2343
+ * @default !process.env.CI
2344
+ */
2345
+ ui?: boolean;
2346
+ /**
2347
+ * Default viewport size
2348
+ */
2349
+ viewport?: {
2350
+ /**
2351
+ * Width of the viewport
2352
+ * @default 414
2353
+ */
2354
+ width: number
2355
+ /**
2356
+ * Height of the viewport
2357
+ * @default 896
2358
+ */
2359
+ height: number
2360
+ };
2361
+ /**
2362
+ * Locator options
2363
+ */
2364
+ locators?: {
2365
+ /**
2366
+ * Attribute used to locate elements by test id
2367
+ * @default 'data-testid'
2368
+ */
2369
+ testIdAttribute?: string
2370
+ };
2371
+ /**
2372
+ * Directory where screenshots will be saved when page.screenshot() is called
2373
+ * If not set, all screenshots are saved to __screenshots__ directory in the same folder as the test file.
2374
+ * If this is set, it will be resolved relative to the project root.
2375
+ * @default __screenshots__
2376
+ */
2377
+ screenshotDirectory?: string;
2378
+ /**
2379
+ * Should Vitest take screenshots if the test fails
2380
+ * @default !browser.ui
2381
+ */
2382
+ screenshotFailures?: boolean;
2383
+ /**
2384
+ * Scripts injected into the tester iframe.
2385
+ * @deprecated Will be removed in the future, use `testerHtmlPath` instead.
2386
+ */
2387
+ testerScripts?: BrowserScript[];
2388
+ /**
2389
+ * Path to the index.html file that will be used to run tests.
2390
+ */
2391
+ testerHtmlPath?: string;
2392
+ /**
2393
+ * Scripts injected into the main window.
2394
+ */
2395
+ orchestratorScripts?: BrowserScript[];
2396
+ /**
2397
+ * Commands that will be executed on the server
2398
+ * via the browser `import("@vitest/browser/context").commands` API.
2399
+ * @see {@link https://vitest.dev/guide/browser/commands}
2400
+ */
2401
+ commands?: Record<string, BrowserCommand<any>>;
2402
+ /**
2403
+ * Timeout for connecting to the browser
2404
+ * @default 30000
2405
+ */
2406
+ connectTimeout?: number;
2407
+ }
2408
+ interface BrowserCommandContext {
2409
+ testPath: string | undefined;
2410
+ provider: BrowserProvider;
2411
+ project: TestProject;
2412
+ /** @deprecated use `sessionId` instead */
2413
+ contextId: string;
2414
+ sessionId: string;
2415
+ }
2416
+ interface BrowserServerStateSession {
2417
+ files: string[];
2418
+ method: "run" | "collect";
2419
+ project: TestProject;
2420
+ connected: () => void;
2421
+ resolve: () => void;
2422
+ reject: (v: unknown) => void;
2423
+ }
2424
+ interface BrowserOrchestrator {
2425
+ createTesters: (files: string[]) => Promise<void>;
2426
+ onCancel: (reason: CancelReason) => Promise<void>;
2427
+ $close: () => void;
2428
+ }
2429
+ interface BrowserServerState {
2430
+ orchestrators: Map<string, BrowserOrchestrator>;
2431
+ }
2432
+ interface ParentProjectBrowser {
2433
+ spawn: (project: TestProject) => ProjectBrowser;
2434
+ }
2435
+ interface ProjectBrowser {
2436
+ vite: ViteDevServer;
2437
+ state: BrowserServerState;
2438
+ provider: BrowserProvider;
2439
+ close: () => Promise<void>;
2440
+ initBrowserProvider: (project: TestProject) => Promise<void>;
2441
+ parseStacktrace: (stack: string) => ParsedStack[];
2442
+ parseErrorStacktrace: (error: ErrorWithDiff, options?: StackTraceParserOptions) => ParsedStack[];
2443
+ }
2444
+ interface BrowserCommand<Payload extends unknown[]> {
2445
+ (context: BrowserCommandContext, ...payload: Payload): Awaitable$1<any>;
2446
+ }
2447
+ interface BrowserScript {
2448
+ /**
2449
+ * If "content" is provided and type is "module", this will be its identifier.
2450
+ *
2451
+ * If you are using TypeScript, you can add `.ts` extension here for example.
2452
+ * @default `injected-${index}.js`
2453
+ */
2454
+ id?: string;
2455
+ /**
2456
+ * JavaScript content to be injected. This string is processed by Vite plugins if type is "module".
2457
+ *
2458
+ * You can use `id` to give Vite a hint about the file extension.
2459
+ */
2460
+ content?: string;
2461
+ /**
2462
+ * Path to the script. This value is resolved by Vite so it can be a node module or a file path.
2463
+ */
2464
+ src?: string;
2465
+ /**
2466
+ * If the script should be loaded asynchronously.
2467
+ */
2468
+ async?: boolean;
2469
+ /**
2470
+ * Script type.
2471
+ * @default 'module'
2472
+ */
2473
+ type?: string;
2474
+ }
2475
+ interface ResolvedBrowserOptions extends BrowserConfigOptions {
2476
+ name: string;
2477
+ providerOptions?: BrowserProviderOptions;
2478
+ enabled: boolean;
2479
+ headless: boolean;
2480
+ isolate: boolean;
2481
+ fileParallelism: boolean;
2482
+ api: ApiConfig;
2483
+ ui: boolean;
2484
+ viewport: {
2485
+ width: number
2486
+ height: number
2487
+ };
2488
+ screenshotFailures: boolean;
2489
+ locators: {
2490
+ testIdAttribute: string
2491
+ };
2492
+ }
2493
+
2494
+ declare class TestProject {
2495
+ /** @deprecated */
2496
+ path: string | number;
2497
+ options?: InitializeProjectOptions | undefined;
2498
+ /**
2499
+ * The global Vitest instance.
2500
+ * @experimental The public Vitest API is experimental and does not follow semver.
2501
+ */
2502
+ readonly vitest: Vitest;
2503
+ /**
2504
+ * Resolved global configuration. If there are no workspace projects, this will be the same as `config`.
2505
+ */
2506
+ readonly globalConfig: ResolvedConfig;
2507
+ /**
2508
+ * Browser instance if the browser is enabled. This is initialized when the tests run for the first time.
2509
+ */
2510
+ browser?: ProjectBrowser;
2511
+ /** @deprecated use `vitest` instead */
2512
+ ctx: Vitest;
2513
+ /**
2514
+ * Temporary directory for the project. This is unique for each project. Vitest stores transformed content here.
2515
+ */
2516
+ readonly tmpDir: string;
2517
+ private runner;
2518
+ private closingPromise;
2519
+ private testFilesList;
2520
+ private typecheckFilesList;
2521
+ private _globalSetups?;
2522
+ private _provided;
2523
+ constructor(path: string | number, vitest: Vitest, options?: InitializeProjectOptions | undefined);
2524
+ /**
2525
+ * Provide a value to the test context. This value will be available to all tests with `inject`.
2526
+ */
2527
+ provide: <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]) => void;
2528
+ /**
2529
+ * Get the provided context. The project context is merged with the global context.
2530
+ */
2531
+ getProvidedContext(): ProvidedContext;
2532
+ /**
2533
+ * Creates a new test specification. Specifications describe how to run tests.
2534
+ * @param moduleId The file path
2535
+ */
2536
+ createSpecification(moduleId: string, locations?: number[] | undefined, pool?: string): TestSpecification;
2537
+ toJSON(): SerializedTestProject;
2538
+ /**
2539
+ * Vite's dev server instance. Every workspace project has its own server.
2540
+ */
2541
+ get vite(): ViteDevServer;
2542
+ /**
2543
+ * Resolved project configuration.
2544
+ */
2545
+ get config(): ResolvedConfig;
2546
+ /**
2547
+ * The name of the project or an empty string if not set.
2548
+ */
2549
+ get name(): string;
2550
+ /**
2551
+ * Serialized project configuration. This is the config that tests receive.
2552
+ */
2553
+ get serializedConfig(): SerializedConfig;
2554
+ /** @deprecated use `vite` instead */
2555
+ get server(): ViteDevServer;
2556
+ /**
2557
+ * Check if this is the root project. The root project is the one that has the root config.
2558
+ */
2559
+ isRootProject(): boolean;
2560
+ /** @deprecated use `isRootProject` instead */
2561
+ isCore(): boolean;
2562
+ /** @deprecated use `createSpecification` instead */
2563
+ createSpec(moduleId: string, pool: string): WorkspaceSpec;
2564
+ /** @deprecated */
2565
+ initializeGlobalSetup(): Promise<void>;
2566
+ onTestsRerun(cb: OnTestsRerunHandler): void;
2567
+ /** @deprecated */
2568
+ teardownGlobalSetup(): Promise<void>;
2569
+ /** @deprecated use `vitest.logger` instead */
2570
+ get logger(): Logger;
2571
+ /** @deprecated use `.vite` or `.browser.vite` directly */
2572
+ getModulesByFilepath(file: string): Set<ModuleNode>;
2573
+ /** @deprecated use `.vite` or `.browser.vite` directly */
2574
+ getModuleById(id: string): ModuleNode | undefined;
2575
+ /** @deprecated use `.vite` or `.browser.vite` directly */
2576
+ getSourceMapModuleById(id: string): TransformResult$1["map"] | undefined;
2577
+ /** @deprecated use `vitest.reporters` instead */
2578
+ get reporters(): Reporter[];
2579
+ /**
2580
+ * Get all files in the project that match the globs in the config and the filters.
2581
+ * @param filters String filters to match the test files.
2582
+ */
2583
+ globTestFiles(filters?: string[]): Promise<{
2584
+ /**
2585
+ * Test files that match the filters.
2586
+ */
2587
+ testFiles: string[]
2588
+ /**
2589
+ * Typecheck test files that match the filters. This will be empty unless `typecheck.enabled` is `true`.
2590
+ */
2591
+ typecheckTestFiles: string[]
2592
+ }>;
2593
+ private globAllTestFiles;
2594
+ isBrowserEnabled(): boolean;
2595
+ private markTestFile;
2596
+ /** @deprecated use `serializedConfig` instead */
2597
+ getSerializableConfig(): SerializedConfig;
2598
+ /**
2599
+ * Test if a file matches the test globs. This does the actual glob matching if the test is not cached, unlike `isCachedTestFile`.
2600
+ */
2601
+ matchesTestGlob(moduleId: string, source?: () => string): boolean;
2602
+ /** @deprecated use `matchesTestGlob` instead */
2603
+ isTargetFile(id: string, source?: string): Promise<boolean>;
2604
+ private isInSourceTestCode;
2605
+ private filterFiles;
2606
+ private _parentBrowser?;
2607
+ private _parent?;
2608
+ /**
2609
+ * Closes the project and all associated resources. This can only be called once; the closing promise is cached until the server restarts.
2610
+ * If the resources are needed again, create a new project.
2611
+ */
2612
+ close(): Promise<void>;
2613
+ /**
2614
+ * Import a file using Vite module runner.
2615
+ * @param moduleId The ID of the module in Vite module graph
2616
+ */
2617
+ import<T>(moduleId: string): Promise<T>;
2618
+ /** @deprecated use `name` instead */
2619
+ getName(): string;
2620
+ /** @deprecated internal */
2621
+ setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
2622
+ private _serializeOverriddenConfig;
2623
+ private clearTmpDir;
2624
+ /** @deprecated */
2625
+ initBrowserProvider(): Promise<void>;
2626
+ }
2627
+
2628
+ interface SerializedTestProject {
2629
+ name: string;
2630
+ serializedConfig: SerializedConfig;
2631
+ context: ProvidedContext;
2632
+ }
2633
+ interface InitializeProjectOptions extends UserWorkspaceConfig {
2634
+ configFile: string | false;
2635
+ }
2636
+
2637
+ /**
2638
+ * @deprecated use TestSpecification instead
2639
+ */
2640
+ type WorkspaceSpec = TestSpecification & [project: TestProject, file: string, options: {
2641
+ pool: Pool
2642
+ }];
2643
+ type RunWithFiles = (files: TestSpecification[], invalidates?: string[]) => Awaitable$1<void>;
2644
+ interface ProcessPool {
2645
+ name: string;
2646
+ runTests: RunWithFiles;
2647
+ collectTests: RunWithFiles;
2648
+ close?: () => Awaitable$1<void>;
2649
+ }
2650
+ declare function getFilePoolName(project: TestProject, file: string): Pool;
2651
+
2652
+ interface TestRunResult {
2653
+ testModules: TestModule[];
2654
+ unhandledErrors: unknown[];
2655
+ }
2656
+
2657
+ interface SuiteResultCache {
2658
+ failed: boolean;
2659
+ duration: number;
2660
+ }
2661
+ declare class ResultsCache {
2662
+ private cache;
2663
+ private workspacesKeyMap;
2664
+ private cachePath;
2665
+ private version;
2666
+ private root;
2667
+ constructor(version: string);
2668
+ getCachePath(): string | null;
2669
+ setConfig(root: string, config: ResolvedConfig["cache"]): void;
2670
+ getResults(key: string): SuiteResultCache | undefined;
2671
+ readFromCache(): Promise<void>;
2672
+ updateResults(files: File[]): void;
2673
+ removeFromCache(filepath: string): void;
2674
+ writeToCache(): Promise<void>;
2675
+ }
2676
+
2677
+ type FileStatsCache = Pick<Stats, "size">;
2678
+ declare class FilesStatsCache {
2679
+ cache: Map<string, FileStatsCache>;
2680
+ getStats(key: string): FileStatsCache | undefined;
2681
+ populateStats(root: string, specs: TestSpecification[]): Promise<void>;
2682
+ updateStats(fsPath: string, key: string): Promise<void>;
2683
+ removeStats(fsPath: string): void;
2684
+ }
2685
+
2686
+ declare class VitestCache {
2687
+ results: ResultsCache;
2688
+ stats: FilesStatsCache;
2689
+ constructor(version: string);
2690
+ getFileTestResults(key: string): SuiteResultCache | undefined;
2691
+ getFileStats(key: string): {
2692
+ size: number
2693
+ } | undefined;
2694
+ static resolveCacheDir(root: string, dir?: string, projectName?: string): string;
2695
+ }
2696
+
2697
+ declare class VitestPackageInstaller {
2698
+ isPackageExists(name: string, options?: {
2699
+ paths?: string[]
2700
+ }): boolean;
2701
+ ensureInstalled(dependency: string, root: string, version?: string): Promise<boolean>;
2702
+ }
2703
+
2704
+ declare class StateManager {
2705
+ filesMap: Map<string, File[]>;
2706
+ pathsSet: Set<string>;
2707
+ idMap: Map<string, Task>;
2708
+ taskFileMap: WeakMap<Task, File>;
2709
+ errorsSet: Set<unknown>;
2710
+ processTimeoutCauses: Set<string>;
2711
+ reportedTasksMap: WeakMap<Task, TestModule | TestCase | TestSuite>;
2712
+ catchError(err: unknown, type: string): void;
2713
+ clearErrors(): void;
2714
+ getUnhandledErrors(): unknown[];
2715
+ addProcessTimeoutCause(cause: string): void;
2716
+ getProcessTimeoutCauses(): string[];
2717
+ getPaths(): string[];
2718
+ /**
2719
+ * Return files that were running or collected.
2720
+ */
2721
+ getFiles(keys?: string[]): File[];
2722
+ getTestModules(keys?: string[]): TestModule[];
2723
+ getFilepaths(): string[];
2724
+ getFailedFilepaths(): string[];
2725
+ collectPaths(paths?: string[]): void;
2726
+ collectFiles(project: TestProject, files?: File[]): void;
2727
+ clearFiles(project: TestProject, paths?: string[]): void;
2728
+ updateId(task: Task, project: TestProject): void;
2729
+ getReportedEntity(task: Task): TestModule | TestCase | TestSuite | undefined;
2730
+ updateTasks(packs: TaskResultPack[]): void;
2731
+ updateUserLog(log: UserConsoleLog): void;
2732
+ getCountOfFailedTests(): number;
2733
+ cancelFiles(files: string[], project: TestProject): void;
2734
+ }
2735
+
2736
+ interface VitestOptions {
2737
+ packageInstaller?: VitestPackageInstaller;
2738
+ stdin?: NodeJS.ReadStream;
2739
+ stdout?: NodeJS.WriteStream | Writable;
2740
+ stderr?: NodeJS.WriteStream | Writable;
2741
+ }
2742
+ declare class Vitest {
2743
+ readonly mode: VitestRunMode;
2744
+ /**
2745
+ * Current Vitest version.
2746
+ * @example '2.0.0'
2747
+ */
2748
+ readonly version: string;
2749
+ static readonly version: string;
2750
+ /**
2751
+ * The logger instance used to log messages. It's recommended to use this logger instead of `console`.
2752
+ * It's possible to override stdout and stderr streams when initiating Vitest.
2753
+ * @example
2754
+ * new Vitest('test', {
2755
+ * stdout: new Writable(),
2756
+ * })
2757
+ */
2758
+ readonly logger: Logger;
2759
+ /**
2760
+ * The package installer instance used to install Vitest packages.
2761
+ * @example
2762
+ * await vitest.packageInstaller.ensureInstalled('@vitest/browser', process.cwd())
2763
+ */
2764
+ readonly packageInstaller: VitestPackageInstaller;
2765
+ /**
2766
+ * A path to the built Vitest directory. This is usually a folder in `node_modules`.
2767
+ */
2768
+ readonly distPath: string;
2769
+ /**
2770
+ * A list of projects that are currently running.
2771
+ * If projects were filtered with `--project` flag, they won't appear here.
2772
+ */
2773
+ projects: TestProject[];
2774
+ private isFirstRun;
2775
+ private restartsCount;
2776
+ private readonly specifications;
2777
+ private readonly watcher;
2778
+ private pool;
2779
+ private _config?;
2780
+ private _vite?;
2781
+ private _state?;
2782
+ private _cache?;
2783
+ private _snapshot?;
2784
+ private _workspaceConfigPath?;
2785
+ constructor(mode: VitestRunMode, options?: VitestOptions);
2786
+ private _onRestartListeners;
2787
+ private _onClose;
2788
+ private _onSetServer;
2789
+ private _onCancelListeners;
2790
+ private _onUserTestsRerun;
2791
+ private _onFilterWatchedSpecification;
2792
+ /** @deprecated will be removed in 4.0, use `onFilterWatchedSpecification` instead */
2793
+ get invalidates(): Set<string>;
2794
+ /** @deprecated will be removed in 4.0, use `onFilterWatchedSpecification` instead */
2795
+ get changedTests(): Set<string>;
2796
+ /**
2797
+ * The global config.
2798
+ */
2799
+ get config(): ResolvedConfig;
2800
+ /** @deprecated use `vitest.vite` instead */
2801
+ get server(): ViteDevServer;
2802
+ /**
2803
+ * Global Vite's dev server instance.
2804
+ */
2805
+ get vite(): ViteDevServer;
2806
+ /**
2807
+ * The global test state manager.
2808
+ * @experimental The State API is experimental and not subject to semver.
2809
+ */
2810
+ get state(): StateManager;
2811
+ /**
2812
+ * The global snapshot manager. You can access the current state on `snapshot.summary`.
2813
+ */
2814
+ get snapshot(): SnapshotManager;
2815
+ /**
2816
+ * Test results and test file stats cache. Primarily used by the sequencer to sort tests.
2817
+ */
2818
+ get cache(): VitestCache;
2819
+ /** @deprecated internal */
2820
+ setServer(options: UserConfig, server: ViteDevServer, cliOptions: UserConfig): Promise<void>;
2821
+ /**
2822
+ * Provide a value to the test context. This value will be available to all tests with `inject`.
2823
+ */
2824
+ provide: <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]) => void;
2825
+ /**
2826
+ * Get global provided context.
2827
+ */
2828
+ getProvidedContext(): ProvidedContext;
2829
+ /** @deprecated use `getRootProject` instead */
2830
+ getCoreWorkspaceProject(): TestProject;
2831
+ /**
2832
+ * Return project that has the root (or "global") config.
2833
+ */
2834
+ getRootProject(): TestProject;
2835
+ /**
2836
+ * @deprecated use Reported Task API instead
2837
+ */
2838
+ getProjectByTaskId(taskId: string): TestProject;
2839
+ getProjectByName(name: string): TestProject;
2840
+ /**
2841
+ * Import a file using Vite module runner. The file will be transformed by Vite and executed in a separate context.
2842
+ * @param moduleId The ID of the module in Vite module graph
2843
+ */
2844
+ import<T>(moduleId: string): Promise<T>;
2845
+ private resolveWorkspaceConfigPath;
2846
+ private resolveWorkspace;
2847
+ /**
2848
+ * Glob test files in every project and create a TestSpecification for each file and pool.
2849
+ * @param filters String filters to match the test files.
2850
+ */
2851
+ globTestSpecifications(filters?: string[]): Promise<TestSpecification[]>;
2852
+ private initCoverageProvider;
2853
+ /**
2854
+ * Merge reports from multiple runs located in the specified directory (value from `--merge-reports` if not specified).
2855
+ */
2856
+ mergeReports(directory?: string): Promise<TestRunResult>;
2857
+ collect(filters?: string[]): Promise<TestRunResult>;
2858
+ /** @deprecated use `getRelevantTestSpecifications` instead */
2859
+ listFiles(filters?: string[]): Promise<TestSpecification[]>;
2860
+ /**
2861
+ * Returns the list of test files that match the config and filters.
2862
+ * @param filters String filters to match the test files
2863
+ */
2864
+ getRelevantTestSpecifications(filters?: string[]): Promise<TestSpecification[]>;
2865
+ /**
2866
+ * Initialize reporters, the coverage provider, and run tests.
2867
+ * This method can throw an error:
2868
+ * - `FilesNotFoundError` if no tests are found
2869
+ * - `GitNotFoundError` if `--related` flag is used, but git repository is not initialized
2870
+ * - `Error` from the user reporters
2871
+ * @param filters String filters to match the test files
2872
+ */
2873
+ start(filters?: string[]): Promise<TestRunResult>;
2874
+ /**
2875
+ * Initialize reporters and the coverage provider. This method doesn't run any tests.
2876
+ * If the `--watch` flag is provided, Vitest will still run changed tests even if this method was not called.
2877
+ */
2878
+ init(): Promise<void>;
2879
+ /**
2880
+ * @deprecated remove when vscode extension supports "getModuleSpecifications"
2881
+ */
2882
+ getProjectsByTestFile(file: string): WorkspaceSpec[];
2883
+ /** @deprecated */
2884
+ getFileWorkspaceSpecs(file: string): WorkspaceSpec[];
2885
+ /**
2886
+ * Get test specifications associated with the given module. If module is not a test file, an empty array is returned.
2887
+ *
2888
+ * **Note:** this method relies on a cache generated by `globTestSpecifications`. If the file was not processed yet, use `project.matchesGlobPattern` instead.
2889
+ * @param moduleId The module ID to get test specifications for.
2890
+ */
2891
+ getModuleSpecifications(moduleId: string): TestSpecification[];
2892
+ /**
2893
+ * Vitest automatically caches test specifications for each file. This method clears the cache for the given file or the whole cache altogether.
2894
+ */
2895
+ clearSpecificationsCache(moduleId?: string): void;
2896
+ /**
2897
+ * Run tests for the given test specifications. This does not trigger `onWatcher*` events.
2898
+ * @param specifications A list of specifications to run.
2899
+ * @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
2900
+ */
2901
+ runTestSpecifications(specifications: TestSpecification[], allTestsRun?: boolean): Promise<TestRunResult>;
2902
+ /**
2903
+ * Rerun files and trigger `onWatcherRerun`, `onWatcherStart` and `onTestsRerun` events.
2904
+ * @param specifications A list of specifications to run.
2905
+ * @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
2906
+ */
2907
+ rerunTestSpecifications(specifications: TestSpecification[], allTestsRun?: boolean): Promise<TestRunResult>;
2908
+ private runFiles;
2909
+ /**
2910
+ * Collect tests in specified modules. Vitest will run the files to collect tests.
2911
+ * @param specifications A list of specifications to run.
2912
+ */
2913
+ collectTests(specifications: TestSpecification[]): Promise<TestRunResult>;
2914
+ /**
2915
+ * Gracefully cancel the current test run. Vitest will wait until all running tests are finished before cancelling.
2916
+ */
2917
+ cancelCurrentRun(reason: CancelReason): Promise<void>;
2918
+ private initializeGlobalSetup;
2919
+ /**
2920
+ * Update snapshots in specified files. If no files are provided, it will update files with failed tests and obsolete snapshots.
2921
+ * @param files The list of files on the file system
2922
+ */
2923
+ updateSnapshot(files?: string[]): Promise<TestRunResult>;
2924
+ /**
2925
+ * Enable the mode that allows updating snapshots when running tests.
2926
+ * This method doesn't run any tests.
2927
+ *
2928
+ * Every test that runs after this method is called will update snapshots.
2929
+ * To disable the mode, call `resetSnapshotUpdate`.
2930
+ */
2931
+ enableSnapshotUpdate(): void;
2932
+ /**
2933
+ * Disable the mode that allows updating snapshots when running tests.
2934
+ */
2935
+ resetSnapshotUpdate(): void;
2936
+ /**
2937
+ * Set the global test name pattern to a regexp.
2938
+ * This method doesn't run any tests.
2939
+ */
2940
+ setGlobalTestNamePattern(pattern: string | RegExp): void;
2941
+ /**
2942
+ * Resets the global test name pattern. This method doesn't run any tests.
2943
+ */
2944
+ resetGlobalTestNamePattern(): void;
2945
+ private _rerunTimer;
2946
+ private scheduleRerun;
2947
+ /**
2948
+ * Invalidate a file in all projects.
2949
+ */
2950
+ invalidateFile(filepath: string): void;
2951
+ /** @deprecated use `invalidateFile` */
2952
+ updateLastChanged(filepath: string): void;
2953
+ private reportCoverage;
2954
+ /**
2955
+ * Closes all projects and their associated resources.
2956
+ * This can only be called once; the closing promise is cached until the server restarts.
2957
+ */
2958
+ close(): Promise<void>;
2959
+ /**
2960
+ * Closes all projects and exit the process
2961
+ * @param force If true, the process will exit immediately after closing the projects.
2962
+ */
2963
+ exit(force?: boolean): Promise<void>;
2964
+ /**
2965
+ * @deprecated use `globTestSpecifications` instead
2966
+ */
2967
+ globTestSpecs(filters?: string[]): Promise<TestSpecification[]>;
2968
+ /**
2969
+ * @deprecated use `globTestSpecifications` instead
2970
+ */
2971
+ globTestFiles(filters?: string[]): Promise<TestSpecification[]>;
2972
+ /** @deprecated filter by `this.projects` yourself */
2973
+ getModuleProjects(filepath: string): TestProject[];
2974
+ /**
2975
+ * Should the server be kept running after the tests are done.
2976
+ */
2977
+ shouldKeepServer(): boolean;
2978
+ /**
2979
+ * Register a handler that will be called when the server is restarted due to a config change.
2980
+ */
2981
+ onServerRestart(fn: OnServerRestartHandler): void;
2982
+ /**
2983
+ * Register a handler that will be called when the test run is cancelled with `vitest.cancelCurrentRun`.
2984
+ */
2985
+ onCancel(fn: (reason: CancelReason) => Awaitable$1<void>): void;
2986
+ /**
2987
+ * Register a handler that will be called when the server is closed.
2988
+ */
2989
+ onClose(fn: () => Awaitable$1<void>): void;
2990
+ /**
2991
+ * Register a handler that will be called when the tests are rerunning.
2992
+ */
2993
+ onTestsRerun(fn: OnTestsRerunHandler): void;
2994
+ /**
2995
+ * Register a handler that will be called when a file is changed.
2996
+ * This callback should return `true` of `false` indicating whether the test file needs to be rerun.
2997
+ * @example
2998
+ * const testsToRun = [resolve('./test.spec.ts')]
2999
+ * vitest.onFilterWatchedSpecification(specification => testsToRun.includes(specification.moduleId))
3000
+ */
3001
+ onFilterWatchedSpecification(fn: (specification: TestSpecification) => boolean): void;
3002
+ }
3003
+ type OnServerRestartHandler = (reason?: string) => Promise<void> | void;
3004
+ type OnTestsRerunHandler = (testFiles: TestSpecification[]) => Promise<void> | void;
3005
+
3006
+ export { type JUnitOptions as $, type ApiConfig as A, type BaseCoverageOptions as B, CoverageMap as C, type DepsOptimizationOptions as D, TestProject as E, type TestSequencer as F, TestSpecification as G, TestModule as H, type InlineConfig as I, type OnTestsRerunHandler as J, VitestPackageInstaller as K, Logger as L, type ModuleDiagnostic as M, type ProcessPool as N, type OnServerRestartHandler as O, type Pool as P, type WorkspaceSpec as Q, type ResolvedCoverageOptions as R, type SerializedTestSpecification as S, type TestProjectConfiguration as T, type UserWorkspaceConfig as U, Vitest as V, type WorkspaceProjectConfiguration as W, getFilePoolName as X, type SerializedTestProject as Y, type HTMLOptions as Z, type JsonOptions$1 as _, type ReportContext as a, type TaskOptions as a0, TestCase as a1, TestCollection as a2, type TestDiagnostic as a3, type TestModuleState as a4, type TestResult as a5, type TestResultFailed as a6, type TestResultPassed as a7, type TestResultSkipped as a8, type TestState as a9, BenchmarkReportsMap as aA, DefaultReporter as aB, DotReporter as aC, GithubActionsReporter as aD, HangingProcessReporter as aE, JsonReporter as aF, JUnitReporter as aG, ReportersMap as aH, TapFlatReporter as aI, TapReporter as aJ, VerboseBenchmarkReporter as aK, VerboseReporter as aL, BaseReporter as aM, type BenchmarkBuiltinReporters as aN, type BuiltinReporterOptions as aO, type BuiltinReporters as aP, type JsonAssertionResult as aQ, type JsonTestResult as aR, type JsonTestResults as aS, TestSuite as aa, type TestSuiteState as ab, type TestSequencerConstructor as ac, type BrowserBuiltinProvider as ad, type BrowserCommand as ae, type BrowserCommandContext as af, type BrowserInstanceOption as ag, type BrowserOrchestrator as ah, type BrowserProvider as ai, type BrowserProviderInitializationOptions as aj, type BrowserProviderModule as ak, type BrowserProviderOptions as al, type BrowserServerState as am, type BrowserServerStateSession as an, type CDPSession as ao, type ParentProjectBrowser as ap, type ProjectBrowser as aq, type ResolvedBrowserOptions as ar, type ResolvedProjectConfig as as, type ResolveSnapshotPathHandler as at, type ResolveSnapshotPathHandlerContext as au, type TestRunResult as av, type ReportedHookContext as aw, type TestRunEndReason as ax, BasicReporter as ay, BenchmarkReporter as az, type CoverageV8Options as b, type UserProjectConfigFn as c, type UserProjectConfigExport as d, type CoverageProvider as e, type CoverageProviderModule as f, type CoverageReporter as g, type CoverageProviderName as h, type CoverageOptions as i, type CoverageIstanbulOptions as j, type CustomProviderOptions as k, type Reporter as l, type BrowserScript as m, type BrowserConfigOptions as n, type BuiltinEnvironment as o, type VitestEnvironment as p, type PoolOptions as q, type CSSModuleScopeStrategy as r, type VitestRunMode as s, type TransformModePatterns as t, type TypecheckConfig as u, type UserConfig as v, type ResolvedConfig as w, type ProjectConfig as x, type BenchmarkUserOptions as y, type VitestOptions as z };