vitest 2.1.5 → 2.2.0-beta.2

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 (45) hide show
  1. package/LICENSE.md +0 -75
  2. package/dist/browser.d.ts +11 -11
  3. package/dist/browser.js +1 -1
  4. package/dist/chunks/{RandomSequencer.CMRlh2v4.js → RandomSequencer.BPedXEug.js} +1 -0
  5. package/dist/chunks/{base.BZZh4cSm.js → base.BS0HhLXd.js} +1 -1
  6. package/dist/chunks/{benchmark.geERunq4.d.ts → benchmark.CFFwLv-O.d.ts} +2 -2
  7. package/dist/chunks/{cac.DWAW3Uh5.js → cac.Cs06pOqp.js} +56 -7
  8. package/dist/chunks/{cli-api.BtqJwSCh.js → cli-api.CB-jIbYQ.js} +585 -407
  9. package/dist/chunks/{config.Cy0C388Z.d.ts → config.CPguQ7J1.d.ts} +2 -1
  10. package/dist/chunks/{environment.LoooBwUu.d.ts → environment.CT0jpO-1.d.ts} +2 -1
  11. package/dist/chunks/{globals.D8ZVAdXd.js → globals.BCGEw6ON.js} +2 -2
  12. package/dist/chunks/{index.nEwtF0bu.js → index.BjjsHdBb.js} +1 -1
  13. package/dist/chunks/{index.ckWaX2gY.js → index.DD5eTY2y.js} +2 -8
  14. package/dist/chunks/{index.DsZFoqi9.js → index.bzFpKeaq.js} +601 -807
  15. package/dist/chunks/{reporters.D7Jzd9GS.d.ts → reporters.F9D2idOT.d.ts} +1429 -1286
  16. package/dist/chunks/{resolveConfig.RxKrDli4.js → resolveConfig.CLnvCvEs.js} +11 -9
  17. package/dist/chunks/{runBaseTests.3qpJUEJM.js → runBaseTests.B7hcVT-s.js} +4 -4
  18. package/dist/chunks/{setup-common.Dj6BZI3u.js → setup-common.BfGt8K-K.js} +4 -1
  19. package/dist/chunks/{suite.B2jumIFP.d.ts → suite.BJU7kdY9.d.ts} +4 -4
  20. package/dist/chunks/{utils.DNoFbBUZ.js → utils.DJONn5B5.js} +15 -21
  21. package/dist/chunks/{vi.DgezovHB.js → vi.BlPttogV.js} +6 -1
  22. package/dist/chunks/{vite.C-N5BBZe.d.ts → vite.DonA4fvH.d.ts} +1 -1
  23. package/dist/chunks/{worker.tN5KGIih.d.ts → worker.9VY11NZs.d.ts} +2 -2
  24. package/dist/chunks/{worker.B9FxPCaC.d.ts → worker.Qz1UB4Fv.d.ts} +1 -1
  25. package/dist/cli.js +1 -1
  26. package/dist/config.d.ts +13 -11
  27. package/dist/coverage.d.ts +9 -112
  28. package/dist/coverage.js +2 -2
  29. package/dist/environments.d.ts +2 -2
  30. package/dist/execute.d.ts +4 -3
  31. package/dist/index.d.ts +14 -13
  32. package/dist/index.js +2 -2
  33. package/dist/node.d.ts +26 -15
  34. package/dist/node.js +9 -9
  35. package/dist/reporters.d.ts +9 -8
  36. package/dist/reporters.js +4 -5
  37. package/dist/runners.d.ts +5 -3
  38. package/dist/runners.js +4 -1
  39. package/dist/suite.d.ts +2 -2
  40. package/dist/workers/forks.js +1 -1
  41. package/dist/workers/runVmTests.js +4 -4
  42. package/dist/workers/threads.js +1 -1
  43. package/dist/workers.d.ts +5 -4
  44. package/dist/workers.js +1 -1
  45. package/package.json +13 -12
@@ -1,19 +1,19 @@
1
1
  import * as _vitest_runner from '@vitest/runner';
2
- import { File, TaskResultPack, Task, Test, Suite, CancelReason, Custom, TaskMeta, SequenceHooks, SequenceSetupFiles } from '@vitest/runner';
3
- import { b as Awaitable, U as UserConsoleLog, P as ProvidedContext, A as AfterSuiteRunMeta, c as Arrayable$1, f as EnvironmentOptions, d as ArgumentsType, O as OnServerRestartHandler } from './environment.LoooBwUu.js';
2
+ import { File, TaskResultPack, Task, Test, Custom, TaskMeta, Suite, SequenceHooks, SequenceSetupFiles, CancelReason } from '@vitest/runner';
3
+ import { b as Awaitable, U as UserConsoleLog, A as AfterSuiteRunMeta, c as Arrayable$1, f as EnvironmentOptions, P as ProvidedContext, d as ArgumentsType, O as OnServerRestartHandler, h as OnTestsRerunHandler } from './environment.CT0jpO-1.js';
4
4
  import { Writable } from 'node:stream';
5
- import * as vite from 'vite';
6
- import { ViteDevServer, TransformResult as TransformResult$1, ServerOptions, DepOptimizationConfig, AliasOptions, UserConfig as UserConfig$1, ConfigEnv } from 'vite';
7
- import { ParsedStack, Awaitable as Awaitable$1, ErrorWithDiff, TestError, Arrayable } from '@vitest/utils';
8
- import { S as SerializedConfig, F as FakeTimerInstallOpts } from './config.Cy0C388Z.js';
5
+ import { TransformResult as TransformResult$1, ServerOptions, DepOptimizationConfig, AliasOptions, UserConfig as UserConfig$1, ConfigEnv, ViteDevServer, ModuleNode } from 'vite';
6
+ import { TestError, ParsedStack, Arrayable, ErrorWithDiff, Awaitable as Awaitable$1 } from '@vitest/utils';
7
+ import { RawSourceMap, ViteNodeServerOptions } from 'vite-node';
8
+ import { StackTraceParserOptions } from '@vitest/utils/source-map';
9
+ import { S as SerializedConfig, F as FakeTimerInstallOpts } from './config.CPguQ7J1.js';
9
10
  import { PrettyFormatOptions } from '@vitest/pretty-format';
10
11
  import { SnapshotSummary, SnapshotStateOptions } from '@vitest/snapshot';
11
- import { RawSourceMap, ViteNodeServerOptions } from 'vite-node';
12
+ import { SerializedDiffOptions } from '@vitest/utils/diff';
12
13
  import * as chai from 'chai';
13
- import { StackTraceParserOptions } from '@vitest/utils/source-map';
14
+ import { B as BenchmarkResult } from './benchmark.CFFwLv-O.js';
14
15
  import { ViteNodeRunner } from 'vite-node/client';
15
16
  import { ViteNodeServer } from 'vite-node/server';
16
- import { B as BenchmarkResult } from './benchmark.geERunq4.js';
17
17
  import { SnapshotManager } from '@vitest/snapshot/manager';
18
18
  import { Stats } from 'node:fs';
19
19
 
@@ -28,8 +28,6 @@ type SerializedTestSpecification = [
28
28
  }
29
29
  ];
30
30
 
31
- type ChaiConfig = Omit<Partial<typeof chai.config>, 'useProxy' | 'proxyExcludedKeys'>;
32
-
33
31
  interface Reporter {
34
32
  onInit?: (ctx: Vitest) => void;
35
33
  onPathsCollected?: (paths?: string[]) => Awaitable<void>;
@@ -55,12 +53,10 @@ declare abstract class BaseReporter implements Reporter {
55
53
  failedUnwatchedFiles: Task[];
56
54
  isTTY: boolean;
57
55
  ctx: Vitest;
56
+ renderSucceed: boolean;
58
57
  protected verbose: boolean;
59
58
  private _filesInWatchMode;
60
59
  private _timeStart;
61
- private _lastRunTimeout;
62
- private _lastRunTimer;
63
- private _lastRunCount;
64
60
  constructor(options?: BaseOptions);
65
61
  onInit(ctx: Vitest): void;
66
62
  log(...messages: any): void;
@@ -71,7 +67,6 @@ declare abstract class BaseReporter implements Reporter {
71
67
  protected printTask(task: Task): void;
72
68
  private getDurationPrefix;
73
69
  onWatcherStart(files?: File[], errors?: unknown[]): void;
74
- private resetLastRunLog;
75
70
  onWatcherRerun(files: string[], trigger?: string): void;
76
71
  onUserConsoleLog(log: UserConsoleLog): void;
77
72
  onTestRemoved(trigger?: string): void;
@@ -84,815 +79,522 @@ declare abstract class BaseReporter implements Reporter {
84
79
  private printTaskErrors;
85
80
  }
86
81
 
87
- interface ParsedFile extends File {
88
- start: number;
89
- end: number;
90
- }
91
- interface ParsedTest extends Test {
92
- start: number;
93
- end: number;
94
- }
95
- interface ParsedSuite extends Suite {
96
- start: number;
97
- end: number;
98
- }
99
- interface LocalCallDefinition {
100
- start: number;
101
- end: number;
102
- name: string;
103
- type: 'suite' | 'test';
104
- mode: 'run' | 'skip' | 'only' | 'todo';
105
- task: ParsedSuite | ParsedFile | ParsedTest;
82
+ interface BlobOptions {
83
+ outputFile?: string;
106
84
  }
107
- interface FileInformation {
108
- file: File;
109
- filepath: string;
110
- parsed: string;
111
- map: RawSourceMap | null;
112
- definitions: LocalCallDefinition[];
85
+ declare class BlobReporter implements Reporter {
86
+ ctx: Vitest;
87
+ options: BlobOptions;
88
+ constructor(options: BlobOptions);
89
+ onInit(ctx: Vitest): void;
90
+ onFinished(files: File[] | undefined, errors: unknown[] | undefined, coverage: unknown): Promise<void>;
113
91
  }
114
92
 
115
- type RawErrsMap = Map<string, TscErrorInfo[]>;
116
- interface TscErrorInfo {
117
- filePath: string;
118
- errCode: number;
119
- errMsg: string;
120
- line: number;
121
- column: number;
122
- }
123
- interface CollectLineNumbers {
124
- target: number;
125
- next: number;
126
- prev?: number;
93
+ interface DefaultReporterOptions extends BaseOptions {
94
+ summary?: boolean;
127
95
  }
128
- type CollectLines = {
129
- [key in keyof CollectLineNumbers]: string;
130
- };
131
- interface RootAndTarget {
132
- root: string;
133
- targetAbsPath: string;
96
+ declare class DefaultReporter extends BaseReporter {
97
+ private options;
98
+ private summary?;
99
+ constructor(options?: DefaultReporterOptions);
100
+ onInit(ctx: Vitest): void;
101
+ onPathsCollected(paths?: string[]): void;
102
+ onTaskUpdate(packs: TaskResultPack[]): void;
103
+ onWatcherRerun(files: string[], trigger?: string): void;
104
+ onFinished(files?: File[], errors?: unknown[]): void;
134
105
  }
135
- type Context = RootAndTarget & {
136
- rawErrsMap: RawErrsMap;
137
- openedDirs: Set<string>;
138
- lastActivePath?: string;
139
- };
140
106
 
141
- declare class TypeCheckError extends Error {
142
- message: string;
143
- stacks: ParsedStack[];
144
- name: string;
145
- constructor(message: string, stacks: ParsedStack[]);
107
+ interface HTMLOptions {
108
+ outputFile?: string;
146
109
  }
147
- interface TypecheckResults {
148
- files: File[];
149
- sourceErrors: TypeCheckError[];
150
- time: number;
110
+
111
+ declare class ReportedTaskImplementation {
112
+ /**
113
+ * Task instance.
114
+ * @experimental Public runner task API is experimental and does not follow semver.
115
+ */
116
+ readonly task: Task;
117
+ /**
118
+ * The project assosiacted with the test or suite.
119
+ */
120
+ readonly project: TestProject;
121
+ /**
122
+ * Unique identifier.
123
+ * This ID is deterministic and will be the same for the same test across multiple runs.
124
+ * The ID is based on the project name, module url and test position.
125
+ */
126
+ readonly id: string;
127
+ /**
128
+ * Location in the module where the test or suite is defined.
129
+ */
130
+ readonly location: {
131
+ line: number;
132
+ column: number;
133
+ } | undefined;
134
+ protected constructor(task: Task, project: TestProject);
135
+ /**
136
+ * Creates a new reported task instance and stores it in the project's state for future use.
137
+ */
138
+ static register(task: Task, project: TestProject): TestCase | TestSuite | TestModule;
151
139
  }
152
- type Callback<Args extends Array<any> = []> = (...args: Args) => Awaitable<void>;
153
- declare class Typechecker {
154
- protected ctx: WorkspaceProject;
155
- private _onParseStart?;
156
- private _onParseEnd?;
157
- private _onWatcherRerun?;
158
- private _result;
159
- private _startTime;
160
- private _output;
161
- private _tests;
162
- private tempConfigPath?;
163
- private allowJs?;
164
- private process?;
165
- protected files: string[];
166
- constructor(ctx: WorkspaceProject);
167
- setFiles(files: string[]): void;
168
- onParseStart(fn: Callback): void;
169
- onParseEnd(fn: Callback<[TypecheckResults]>): void;
170
- onWatcherRerun(fn: Callback): void;
171
- protected collectFileTests(filepath: string): Promise<FileInformation | null>;
172
- protected getFiles(): string[];
173
- collectTests(): Promise<Record<string, FileInformation>>;
174
- protected markPassed(file: File): void;
175
- protected prepareResults(output: string): Promise<{
176
- files: File[];
177
- sourceErrors: TypeCheckError[];
178
- time: number;
179
- }>;
180
- protected parseTscLikeOutput(output: string): Promise<Map<string, {
181
- error: TypeCheckError;
182
- originalError: TscErrorInfo;
183
- }[]>>;
184
- clear(): Promise<void>;
185
- stop(): Promise<void>;
186
- protected ensurePackageInstalled(ctx: Vitest, checker: string): Promise<void>;
187
- prepare(): Promise<void>;
188
- getExitCode(): number | false;
189
- getOutput(): string;
190
- start(): Promise<void>;
191
- getResult(): TypecheckResults;
192
- getTestFiles(): File[];
193
- getTestPacks(): TaskResultPack[];
140
+ declare class TestCase extends ReportedTaskImplementation {
141
+ #private;
142
+ readonly task: Test | Custom;
143
+ readonly type = "test";
144
+ /**
145
+ * Direct reference to the test module where the test or suite is defined.
146
+ */
147
+ readonly module: TestModule;
148
+ /**
149
+ * Name of the test.
150
+ */
151
+ readonly name: string;
152
+ /**
153
+ * Options that the test was initiated with.
154
+ */
155
+ readonly options: TaskOptions;
156
+ /**
157
+ * Parent suite. If the test was called directly inside the module, the parent will be the module itself.
158
+ */
159
+ readonly parent: TestSuite | TestModule;
160
+ protected constructor(task: Test | Custom, project: TestProject);
161
+ /**
162
+ * Full name of the test including all parent suites separated with `>`.
163
+ */
164
+ get fullName(): string;
165
+ /**
166
+ * Test results. Will be `undefined` if test is not finished yet or was just collected.
167
+ */
168
+ result(): TestResult | undefined;
169
+ /**
170
+ * Checks if the test did not fail the suite.
171
+ * If the test is not finished yet or was skipped, it will return `true`.
172
+ */
173
+ ok(): boolean;
174
+ /**
175
+ * Custom metadata that was attached to the test during its execution.
176
+ */
177
+ meta(): TaskMeta;
178
+ /**
179
+ * Useful information about the test like duration, memory usage, etc.
180
+ * Diagnostic is only available after the test has finished.
181
+ */
182
+ diagnostic(): TestDiagnostic | undefined;
194
183
  }
195
-
196
- interface PrintErrorResult {
197
- nearest?: ParsedStack;
184
+ declare class TestCollection {
185
+ #private;
186
+ constructor(task: Suite | File, project: TestProject);
187
+ /**
188
+ * Returns the test or suite at a specific index in the array.
189
+ */
190
+ at(index: number): TestCase | TestSuite | undefined;
191
+ /**
192
+ * The number of tests and suites in the collection.
193
+ */
194
+ get size(): number;
195
+ /**
196
+ * Returns the collection in array form for easier manipulation.
197
+ */
198
+ array(): (TestCase | TestSuite)[];
199
+ /**
200
+ * Filters all tests that are part of this collection and its children.
201
+ */
202
+ allTests(state?: TestResult['state'] | 'running'): Generator<TestCase, undefined, void>;
203
+ /**
204
+ * Filters only the tests that are part of this collection.
205
+ */
206
+ tests(state?: TestResult['state'] | 'running'): Generator<TestCase, undefined, void>;
207
+ /**
208
+ * Filters only the suites that are part of this collection.
209
+ */
210
+ suites(): Generator<TestSuite, undefined, void>;
211
+ /**
212
+ * Filters all suites that are part of this collection and its children.
213
+ */
214
+ allSuites(): Generator<TestSuite, undefined, void>;
215
+ [Symbol.iterator](): Generator<TestSuite | TestCase, undefined, void>;
198
216
  }
199
217
 
200
- interface Options {
201
- /**
202
- Show the cursor. This can be useful when a CLI accepts input from a user.
203
-
204
- @example
205
- ```
206
- import {createLogUpdate} from 'log-update';
207
-
208
- // Write output but don't hide the cursor
209
- const log = createLogUpdate(process.stdout, {
210
- showCursor: true
211
- });
212
- ```
213
- */
214
- readonly showCursor?: boolean;
218
+ declare abstract class SuiteImplementation extends ReportedTaskImplementation {
219
+ readonly task: Suite | File;
220
+ /**
221
+ * Collection of suites and tests that are part of this suite.
222
+ */
223
+ readonly children: TestCollection;
224
+ protected constructor(task: Suite | File, project: TestProject);
215
225
  }
216
-
217
- type LogUpdateMethods = {
218
- /**
219
- Clear the logged output.
220
- */
221
- clear(): void;
222
-
223
- /**
224
- Persist the logged output. Useful if you want to start a new log session below the current one.
225
- */
226
- done(): void;
227
- };
228
-
229
- /**
230
- Log to `stdout` by overwriting the previous output in the terminal.
231
-
232
- @param text - The text to log to `stdout`.
233
-
234
- @example
235
- ```
236
- import logUpdate from 'log-update';
237
-
238
- const frames = ['-', '\\', '|', '/'];
239
- let index = 0;
240
-
241
- setInterval(() => {
242
- const frame = frames[index = ++index % frames.length];
243
-
244
- logUpdate(
245
- `
246
- ♥♥
247
- ${frame} unicorns ${frame}
248
- ♥♥
249
- `
250
- );
251
- }, 80);
252
- ```
253
- */
254
- declare const logUpdate: ((...text: string[]) => void) & LogUpdateMethods;
255
-
256
-
257
- /**
258
- Get a `logUpdate` method that logs to the specified stream.
259
-
260
- @param stream - The stream to log to.
261
-
262
- @example
263
- ```
264
- import {createLogUpdate} from 'log-update';
265
-
266
- // Write output but don't hide the cursor
267
- const log = createLogUpdate(process.stdout);
268
- ```
269
- */
270
- declare function createLogUpdate(
271
- stream: NodeJS.WritableStream,
272
- options?: Options
273
- ): typeof logUpdate;
274
-
275
- interface ErrorOptions {
276
- type?: string;
277
- fullStack?: boolean;
278
- project?: WorkspaceProject;
279
- verbose?: boolean;
280
- screenshotPaths?: string[];
281
- task?: Task;
282
- showCodeFrame?: boolean;
283
- }
284
- declare class Logger {
285
- ctx: Vitest;
286
- outputStream: NodeJS.WriteStream | Writable;
287
- errorStream: NodeJS.WriteStream | Writable;
288
- logUpdate: ReturnType<typeof createLogUpdate>;
289
- private _clearScreenPending;
290
- private _highlights;
291
- console: Console;
292
- constructor(ctx: Vitest, outputStream?: NodeJS.WriteStream | Writable, errorStream?: NodeJS.WriteStream | Writable);
293
- log(...args: any[]): void;
294
- error(...args: any[]): void;
295
- warn(...args: any[]): void;
296
- clearFullScreen(message?: string): void;
297
- clearScreen(message: string, force?: boolean): void;
298
- private _clearScreen;
299
- printError(err: unknown, options?: ErrorOptions): PrintErrorResult | undefined;
300
- clearHighlightCache(filename?: string): void;
301
- highlight(filename: string, source: string): string;
302
- printNoTestFound(filters?: string[]): void;
303
- printBanner(): void;
304
- printBrowserBanner(project: WorkspaceProject): void;
305
- printUnhandledErrors(errors: unknown[]): void;
306
- printSourceTypeErrors(errors: TypeCheckError[]): void;
307
- private registerUnhandledRejection;
308
- }
309
-
310
- interface BrowserProviderInitializationOptions {
311
- browser: string;
312
- options?: BrowserProviderOptions;
313
- }
314
- interface CDPSession {
315
- send: (method: string, params?: Record<string, unknown>) => Promise<unknown>;
316
- on: (event: string, listener: (...args: unknown[]) => void) => void;
317
- once: (event: string, listener: (...args: unknown[]) => void) => void;
318
- off: (event: string, listener: (...args: unknown[]) => void) => void;
319
- }
320
- interface BrowserProvider {
321
- name: string;
226
+ declare class TestSuite extends SuiteImplementation {
227
+ #private;
228
+ readonly task: Suite;
229
+ readonly type = "suite";
322
230
  /**
323
- * @experimental opt-in into file parallelisation
231
+ * Name of the test or the suite.
324
232
  */
325
- supportsParallelism: boolean;
326
- getSupportedBrowsers: () => readonly string[];
327
- beforeCommand?: (command: string, args: unknown[]) => Awaitable$1<void>;
328
- afterCommand?: (command: string, args: unknown[]) => Awaitable$1<void>;
329
- getCommandsContext: (contextId: string) => Record<string, unknown>;
330
- openPage: (contextId: string, url: string, beforeNavigate?: () => Promise<void>) => Promise<void>;
331
- getCDPSession?: (contextId: string) => Promise<CDPSession>;
332
- close: () => Awaitable$1<void>;
333
- initialize(ctx: WorkspaceProject, options: BrowserProviderInitializationOptions): Awaitable$1<void>;
334
- }
335
- interface BrowserProviderModule {
336
- new (): BrowserProvider;
337
- }
338
- interface BrowserProviderOptions {
339
- }
340
- type BrowserBuiltinProvider = 'webdriverio' | 'playwright' | 'preview';
341
- interface BrowserConfigOptions {
233
+ readonly name: string;
342
234
  /**
343
- * if running tests in the browser should be the default
344
- *
345
- * @default false
235
+ * Direct reference to the test module where the test or suite is defined.
346
236
  */
347
- enabled?: boolean;
237
+ readonly module: TestModule;
348
238
  /**
349
- * Name of the browser
239
+ * Parent suite. If suite was called directly inside the module, the parent will be the module itself.
350
240
  */
351
- name: string;
241
+ readonly parent: TestSuite | TestModule;
352
242
  /**
353
- * Browser provider
354
- *
355
- * @default 'preview'
243
+ * Options that suite was initiated with.
356
244
  */
357
- provider?: BrowserBuiltinProvider | (string & {});
245
+ readonly options: TaskOptions;
246
+ protected constructor(task: Suite, project: TestProject);
358
247
  /**
359
- * Options that are passed down to a browser provider.
360
- * To support type hinting, add one of the types to your tsconfig.json "compilerOptions.types" field:
361
- *
362
- * - for webdriverio: `@vitest/browser/providers/webdriverio`
363
- * - for playwright: `@vitest/browser/providers/playwright`
364
- *
365
- * @example
366
- * { playwright: { launch: { devtools: true } }
248
+ * Full name of the suite including all parent suites separated with `>`.
367
249
  */
368
- providerOptions?: BrowserProviderOptions;
250
+ get fullName(): string;
251
+ }
252
+ declare class TestModule extends SuiteImplementation {
253
+ readonly task: File;
254
+ readonly location: undefined;
255
+ readonly type = "module";
369
256
  /**
370
- * enable headless mode
371
- *
372
- * @default process.env.CI
257
+ * This is usually an absolute UNIX file path.
258
+ * It can be a virtual id if the file is not on the disk.
259
+ * This value corresponds to Vite's `ModuleGraph` id.
373
260
  */
374
- headless?: boolean;
261
+ readonly moduleId: string;
262
+ protected constructor(task: File, project: TestProject);
375
263
  /**
376
- * Serve API options.
377
- *
378
- * The default port is 63315.
264
+ * Useful information about the module like duration, memory usage, etc.
265
+ * If the module was not executed yet, all diagnostic values will return `0`.
379
266
  */
380
- api?: ApiConfig | number;
267
+ diagnostic(): ModuleDiagnostic;
268
+ }
269
+ interface TaskOptions {
270
+ each: boolean | undefined;
271
+ concurrent: boolean | undefined;
272
+ shuffle: boolean | undefined;
273
+ retry: number | undefined;
274
+ repeats: number | undefined;
275
+ mode: 'run' | 'only' | 'skip' | 'todo';
276
+ }
277
+ type TestResult = TestResultPassed | TestResultFailed | TestResultSkipped;
278
+ interface TestResultPassed {
381
279
  /**
382
- * Isolate test environment after each test
383
- *
384
- * @default true
280
+ * The test passed successfully.
385
281
  */
386
- isolate?: boolean;
282
+ state: 'passed';
387
283
  /**
388
- * Run test files in parallel if provider supports this option
389
- * This option only has effect in headless mode (enabled in CI by default)
284
+ * Errors that were thrown during the test execution.
390
285
  *
391
- * @default // Same as "test.fileParallelism"
286
+ * **Note**: If test was retried successfully, errors will still be reported.
392
287
  */
393
- fileParallelism?: boolean;
288
+ errors: TestError[] | undefined;
289
+ }
290
+ interface TestResultFailed {
394
291
  /**
395
- * Show Vitest UI
396
- *
397
- * @default !process.env.CI
292
+ * The test failed to execute.
398
293
  */
399
- ui?: boolean;
294
+ state: 'failed';
400
295
  /**
401
- * Default viewport size
296
+ * Errors that were thrown during the test execution.
402
297
  */
403
- viewport?: {
404
- /**
405
- * Width of the viewport
406
- * @default 414
407
- */
408
- width: number;
409
- /**
410
- * Height of the viewport
411
- * @default 896
412
- */
413
- height: number;
414
- };
298
+ errors: TestError[];
299
+ }
300
+ interface TestResultSkipped {
415
301
  /**
416
- * Locator options
302
+ * The test was skipped with `only`, `skip` or `todo` flag.
303
+ * You can see which one was used in the `mode` option.
417
304
  */
418
- locators?: {
419
- /**
420
- * Attribute used to locate elements by test id
421
- * @default 'data-testid'
422
- */
423
- testIdAttribute?: string;
424
- };
305
+ state: 'skipped';
425
306
  /**
426
- * Directory where screenshots will be saved when page.screenshot() is called
427
- * If not set, all screenshots are saved to __screenshots__ directory in the same folder as the test file.
428
- * If this is set, it will be resolved relative to the project root.
429
- * @default __screenshots__
307
+ * Skipped tests have no errors.
430
308
  */
431
- screenshotDirectory?: string;
309
+ errors: undefined;
432
310
  /**
433
- * Should Vitest take screenshots if the test fails
434
- * @default !browser.ui
311
+ * A custom note.
435
312
  */
436
- screenshotFailures?: boolean;
313
+ note: string | undefined;
314
+ }
315
+ interface TestDiagnostic {
437
316
  /**
438
- * Scripts injected into the tester iframe.
439
- * @deprecated Will be removed in the future, use `testerHtmlPath` instead.
317
+ * If the duration of the test is above `slowTestThreshold`.
440
318
  */
441
- testerScripts?: BrowserScript[];
319
+ slow: boolean;
442
320
  /**
443
- * Path to the index.html file that will be used to run tests.
321
+ * The amount of memory used by the test in bytes.
322
+ * This value is only available if the test was executed with `logHeapUsage` flag.
444
323
  */
445
- testerHtmlPath?: string;
324
+ heap: number | undefined;
446
325
  /**
447
- * Scripts injected into the main window.
326
+ * The time it takes to execute the test in ms.
448
327
  */
449
- orchestratorScripts?: BrowserScript[];
328
+ duration: number;
450
329
  /**
451
- * Commands that will be executed on the server
452
- * via the browser `import("@vitest/browser/context").commands` API.
453
- * @see {@link https://vitest.dev/guide/browser/commands}
330
+ * The time in ms when the test started.
454
331
  */
455
- commands?: Record<string, BrowserCommand<any>>;
456
- }
457
- interface BrowserCommandContext {
458
- testPath: string | undefined;
459
- provider: BrowserProvider;
460
- project: WorkspaceProject;
461
- contextId: string;
462
- }
463
- interface BrowserServerStateContext {
464
- files: string[];
465
- method: 'run' | 'collect';
466
- resolve: () => void;
467
- reject: (v: unknown) => void;
468
- }
469
- interface BrowserOrchestrator {
470
- createTesters: (files: string[]) => Promise<void>;
471
- onCancel: (reason: CancelReason) => Promise<void>;
472
- $close: () => void;
473
- }
474
- interface BrowserServerState {
475
- orchestrators: Map<string, BrowserOrchestrator>;
476
- getContext: (contextId: string) => BrowserServerStateContext | undefined;
477
- createAsyncContext: (method: 'collect' | 'run', contextId: string, files: string[]) => Promise<void>;
478
- }
479
- interface BrowserServer {
480
- vite: ViteDevServer;
481
- state: BrowserServerState;
482
- provider: BrowserProvider;
483
- close: () => Promise<void>;
484
- initBrowserProvider: () => Promise<void>;
485
- parseStacktrace: (stack: string) => ParsedStack[];
486
- parseErrorStacktrace: (error: ErrorWithDiff, options?: StackTraceParserOptions) => ParsedStack[];
487
- }
488
- interface BrowserCommand<Payload extends unknown[]> {
489
- (context: BrowserCommandContext, ...payload: Payload): Awaitable$1<any>;
490
- }
491
- interface BrowserScript {
492
- /**
493
- * If "content" is provided and type is "module", this will be its identifier.
494
- *
495
- * If you are using TypeScript, you can add `.ts` extension here for example.
496
- * @default `injected-${index}.js`
497
- */
498
- id?: string;
499
- /**
500
- * JavaScript content to be injected. This string is processed by Vite plugins if type is "module".
501
- *
502
- * You can use `id` to give Vite a hint about the file extension.
503
- */
504
- content?: string;
505
- /**
506
- * Path to the script. This value is resolved by Vite so it can be a node module or a file path.
507
- */
508
- src?: string;
509
- /**
510
- * If the script should be loaded asynchronously.
511
- */
512
- async?: boolean;
513
- /**
514
- * Script type.
515
- * @default 'module'
516
- */
517
- type?: string;
518
- }
519
- interface ResolvedBrowserOptions extends BrowserConfigOptions {
520
- enabled: boolean;
521
- headless: boolean;
522
- isolate: boolean;
523
- fileParallelism: boolean;
524
- api: ApiConfig;
525
- ui: boolean;
526
- viewport: {
527
- width: number;
528
- height: number;
529
- };
530
- screenshotFailures: boolean;
531
- locators: {
532
- testIdAttribute: string;
533
- };
534
- }
535
-
536
- interface InitializeProjectOptions extends UserWorkspaceConfig {
537
- workspaceConfigPath: string;
538
- extends?: string;
539
- }
540
- declare class WorkspaceProject {
541
- path: string | number;
542
- ctx: Vitest;
543
- options?: InitializeProjectOptions | undefined;
544
- configOverride: Partial<ResolvedConfig> | undefined;
545
- config: ResolvedConfig;
546
- server: ViteDevServer;
547
- vitenode: ViteNodeServer;
548
- runner: ViteNodeRunner;
549
- browser?: BrowserServer;
550
- typechecker?: Typechecker;
551
- closingPromise: Promise<unknown> | undefined;
552
- testFilesList: string[] | null;
553
- typecheckFilesList: string[] | null;
554
- testProject: TestProject;
555
- readonly id: string;
556
- readonly tmpDir: string;
557
- private _globalSetups;
558
- private _provided;
559
- constructor(path: string | number, ctx: Vitest, options?: InitializeProjectOptions | undefined);
560
- getName(): string;
561
- isCore(): boolean;
562
- provide<T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]): void;
563
- getProvidedContext(): ProvidedContext;
564
- createSpec(moduleId: string, pool: string): WorkspaceSpec;
565
- initializeGlobalSetup(): Promise<void>;
566
- teardownGlobalSetup(): Promise<void>;
567
- get logger(): Logger;
568
- getModulesByFilepath(file: string): Set<vite.ModuleNode>;
569
- getModuleById(id: string): vite.ModuleNode | undefined;
570
- getSourceMapModuleById(id: string): TransformResult$1['map'] | undefined;
571
- get reporters(): Reporter[];
572
- globTestFiles(filters?: string[]): Promise<{
573
- testFiles: string[];
574
- typecheckTestFiles: string[];
575
- }>;
576
- globAllTestFiles(include: string[], exclude: string[], includeSource: string[] | undefined, cwd: string): Promise<string[]>;
577
- isTestFile(id: string): boolean | null;
578
- isTypecheckFile(id: string): boolean | null;
579
- globFiles(include: string[], exclude: string[], cwd: string): Promise<string[]>;
580
- isTargetFile(id: string, source?: string): Promise<boolean>;
581
- isInSourceTestFile(code: string): boolean;
582
- filterFiles(testFiles: string[], filters: string[], dir: string): string[];
583
- initBrowserServer(): Promise<void>;
584
- static createBasicProject(ctx: Vitest): WorkspaceProject;
585
- static createCoreProject(ctx: Vitest): Promise<WorkspaceProject>;
586
- setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
587
- isBrowserEnabled(): boolean;
588
- getSerializableConfig(): SerializedConfig;
589
- close(): Promise<unknown>;
590
- private clearTmpDir;
591
- initBrowserProvider(): Promise<void>;
592
- }
593
-
594
- interface BlobOptions {
595
- outputFile?: string;
596
- }
597
- declare class BlobReporter implements Reporter {
598
- ctx: Vitest;
599
- options: BlobOptions;
600
- constructor(options: BlobOptions);
601
- onInit(ctx: Vitest): void;
602
- onFinished(files: File[] | undefined, errors: unknown[] | undefined, coverage: unknown): Promise<void>;
603
- }
604
-
605
- interface HTMLOptions {
606
- outputFile?: string;
607
- }
608
-
609
- declare class ReportedTaskImplementation {
610
- /**
611
- * Task instance.
612
- * @experimental Public runner task API is experimental and does not follow semver.
613
- */
614
- readonly task: Task;
615
- /**
616
- * The project assosiacted with the test or suite.
617
- */
618
- readonly project: TestProject;
332
+ startTime: number;
619
333
  /**
620
- * Unique identifier.
621
- * This ID is deterministic and will be the same for the same test across multiple runs.
622
- * The ID is based on the project name, module url and test position.
334
+ * The amount of times the test was retried.
623
335
  */
624
- readonly id: string;
336
+ retryCount: number;
625
337
  /**
626
- * Location in the module where the test or suite is defined.
338
+ * The amount of times the test was repeated as configured by `repeats` option.
339
+ * This value can be lower if the test failed during the repeat and no `retry` is configured.
627
340
  */
628
- readonly location: {
629
- line: number;
630
- column: number;
631
- } | undefined;
632
- protected constructor(task: Task, project: WorkspaceProject);
341
+ repeatCount: number;
633
342
  /**
634
- * Creates a new reported task instance and stores it in the project's state for future use.
343
+ * If test passed on a second retry.
635
344
  */
636
- static register(task: Task, project: WorkspaceProject): TestCase | TestSuite | TestModule;
345
+ flaky: boolean;
637
346
  }
638
- declare class TestCase extends ReportedTaskImplementation {
639
- #private;
640
- readonly task: Test | Custom;
641
- readonly type = "test";
642
- /**
643
- * Direct reference to the test module where the test or suite is defined.
644
- */
645
- readonly module: TestModule;
646
- /**
647
- * Name of the test.
648
- */
649
- readonly name: string;
650
- /**
651
- * Options that the test was initiated with.
652
- */
653
- readonly options: TaskOptions;
654
- /**
655
- * Parent suite. If the test was called directly inside the module, the parent will be the module itself.
656
- */
657
- readonly parent: TestSuite | TestModule;
658
- protected constructor(task: Test | Custom, project: WorkspaceProject);
347
+ interface ModuleDiagnostic {
659
348
  /**
660
- * Full name of the test including all parent suites separated with `>`.
349
+ * The time it takes to import and initiate an environment.
661
350
  */
662
- get fullName(): string;
351
+ environmentSetupDuration: number;
663
352
  /**
664
- * Test results. Will be `undefined` if test is not finished yet or was just collected.
353
+ * The time it takes Vitest to setup test harness (runner, mocks, etc.).
665
354
  */
666
- result(): TestResult | undefined;
355
+ prepareDuration: number;
667
356
  /**
668
- * Checks if the test did not fail the suite.
669
- * If the test is not finished yet or was skipped, it will return `true`.
357
+ * The time it takes to import the test module.
358
+ * This includes importing everything in the module and executing suite callbacks.
670
359
  */
671
- ok(): boolean;
360
+ collectDuration: number;
672
361
  /**
673
- * Custom metadata that was attached to the test during its execution.
362
+ * The time it takes to import the setup module.
674
363
  */
675
- meta(): TaskMeta;
364
+ setupDuration: number;
676
365
  /**
677
- * Useful information about the test like duration, memory usage, etc.
678
- * Diagnostic is only available after the test has finished.
366
+ * Accumulated duration of all tests and hooks in the module.
679
367
  */
680
- diagnostic(): TestDiagnostic | undefined;
368
+ duration: number;
681
369
  }
682
- declare class TestCollection {
683
- #private;
684
- constructor(task: Suite | File, project: WorkspaceProject);
685
- /**
686
- * Returns the test or suite at a specific index in the array.
687
- */
688
- at(index: number): TestCase | TestSuite | undefined;
689
- /**
690
- * The number of tests and suites in the collection.
691
- */
692
- get size(): number;
693
- /**
694
- * Returns the collection in array form for easier manipulation.
695
- */
696
- array(): (TestCase | TestSuite)[];
697
- /**
698
- * Filters all tests that are part of this collection and its children.
699
- */
700
- allTests(state?: TestResult['state'] | 'running'): Generator<TestCase, undefined, void>;
701
- /**
702
- * Filters only the tests that are part of this collection.
703
- */
704
- tests(state?: TestResult['state'] | 'running'): Generator<TestCase, undefined, void>;
705
- /**
706
- * Filters only the suites that are part of this collection.
707
- */
708
- suites(): Generator<TestSuite, undefined, void>;
709
- /**
710
- * Filters all suites that are part of this collection and its children.
711
- */
712
- allSuites(): Generator<TestSuite, undefined, void>;
713
- [Symbol.iterator](): Generator<TestSuite | TestCase, undefined, void>;
370
+
371
+ declare class BasicReporter extends BaseReporter {
372
+ constructor();
373
+ onInit(ctx: Vitest): void;
374
+ reportSummary(files: File[], errors: unknown[]): void;
714
375
  }
715
376
 
716
- declare abstract class SuiteImplementation extends ReportedTaskImplementation {
717
- readonly task: Suite | File;
718
- /**
719
- * Collection of suites and tests that are part of this suite.
720
- */
721
- readonly children: TestCollection;
722
- protected constructor(task: Suite | File, project: WorkspaceProject);
377
+ interface ParsedFile extends File {
378
+ start: number;
379
+ end: number;
723
380
  }
724
- declare class TestSuite extends SuiteImplementation {
725
- #private;
726
- readonly task: Suite;
727
- readonly type = "suite";
728
- /**
729
- * Name of the test or the suite.
730
- */
731
- readonly name: string;
732
- /**
733
- * Direct reference to the test module where the test or suite is defined.
734
- */
735
- readonly module: TestModule;
736
- /**
737
- * Parent suite. If suite was called directly inside the module, the parent will be the module itself.
738
- */
739
- readonly parent: TestSuite | TestModule;
740
- /**
741
- * Options that suite was initiated with.
742
- */
743
- readonly options: TaskOptions;
744
- protected constructor(task: Suite, project: WorkspaceProject);
745
- /**
746
- * Full name of the suite including all parent suites separated with `>`.
747
- */
748
- get fullName(): string;
381
+ interface ParsedTest extends Test {
382
+ start: number;
383
+ end: number;
749
384
  }
750
- declare class TestModule extends SuiteImplementation {
751
- readonly task: File;
752
- readonly location: undefined;
753
- readonly type = "module";
754
- /**
755
- * This is usually an absolute UNIX file path.
756
- * It can be a virtual id if the file is not on the disk.
757
- * This value corresponds to Vite's `ModuleGraph` id.
758
- */
759
- readonly moduleId: string;
760
- protected constructor(task: File, project: WorkspaceProject);
761
- /**
762
- * Useful information about the module like duration, memory usage, etc.
763
- * If the module was not executed yet, all diagnostic values will return `0`.
764
- */
765
- diagnostic(): ModuleDiagnostic;
385
+ interface ParsedSuite extends Suite {
386
+ start: number;
387
+ end: number;
766
388
  }
767
- interface TaskOptions {
768
- each: boolean | undefined;
769
- concurrent: boolean | undefined;
770
- shuffle: boolean | undefined;
771
- retry: number | undefined;
772
- repeats: number | undefined;
773
- mode: 'run' | 'only' | 'skip' | 'todo';
389
+ interface LocalCallDefinition {
390
+ start: number;
391
+ end: number;
392
+ name: string;
393
+ type: 'suite' | 'test';
394
+ mode: 'run' | 'skip' | 'only' | 'todo';
395
+ task: ParsedSuite | ParsedFile | ParsedTest;
774
396
  }
775
- type TestResult = TestResultPassed | TestResultFailed | TestResultSkipped;
776
- interface TestResultPassed {
777
- /**
778
- * The test passed successfully.
779
- */
780
- state: 'passed';
781
- /**
782
- * Errors that were thrown during the test execution.
783
- *
784
- * **Note**: If test was retried successfully, errors will still be reported.
785
- */
786
- errors: TestError[] | undefined;
397
+ interface FileInformation {
398
+ file: File;
399
+ filepath: string;
400
+ parsed: string;
401
+ map: RawSourceMap | null;
402
+ definitions: LocalCallDefinition[];
787
403
  }
788
- interface TestResultFailed {
789
- /**
790
- * The test failed to execute.
791
- */
792
- state: 'failed';
793
- /**
794
- * Errors that were thrown during the test execution.
795
- */
796
- errors: TestError[];
404
+
405
+ type RawErrsMap = Map<string, TscErrorInfo[]>;
406
+ interface TscErrorInfo {
407
+ filePath: string;
408
+ errCode: number;
409
+ errMsg: string;
410
+ line: number;
411
+ column: number;
797
412
  }
798
- interface TestResultSkipped {
799
- /**
800
- * The test was skipped with `only`, `skip` or `todo` flag.
801
- * You can see which one was used in the `mode` option.
802
- */
803
- state: 'skipped';
804
- /**
805
- * Skipped tests have no errors.
806
- */
807
- errors: undefined;
413
+ interface CollectLineNumbers {
414
+ target: number;
415
+ next: number;
416
+ prev?: number;
417
+ }
418
+ type CollectLines = {
419
+ [key in keyof CollectLineNumbers]: string;
420
+ };
421
+ interface RootAndTarget {
422
+ root: string;
423
+ targetAbsPath: string;
424
+ }
425
+ type Context = RootAndTarget & {
426
+ rawErrsMap: RawErrsMap;
427
+ openedDirs: Set<string>;
428
+ lastActivePath?: string;
429
+ };
430
+
431
+ declare class TypeCheckError extends Error {
432
+ message: string;
433
+ stacks: ParsedStack[];
434
+ name: string;
435
+ constructor(message: string, stacks: ParsedStack[]);
808
436
  }
809
- interface TestDiagnostic {
810
- /**
811
- * If the duration of the test is above `slowTestThreshold`.
812
- */
813
- slow: boolean;
814
- /**
815
- * The amount of memory used by the test in bytes.
816
- * This value is only available if the test was executed with `logHeapUsage` flag.
817
- */
818
- heap: number | undefined;
819
- /**
820
- * The time it takes to execute the test in ms.
821
- */
822
- duration: number;
823
- /**
824
- * The time in ms when the test started.
825
- */
826
- startTime: number;
827
- /**
828
- * The amount of times the test was retried.
829
- */
830
- retryCount: number;
831
- /**
832
- * The amount of times the test was repeated as configured by `repeats` option.
833
- * This value can be lower if the test failed during the repeat and no `retry` is configured.
834
- */
835
- repeatCount: number;
836
- /**
837
- * If test passed on a second retry.
838
- */
839
- flaky: boolean;
437
+ interface TypecheckResults {
438
+ files: File[];
439
+ sourceErrors: TypeCheckError[];
440
+ time: number;
840
441
  }
841
- interface ModuleDiagnostic {
842
- /**
843
- * The time it takes to import and initiate an environment.
844
- */
845
- environmentSetupDuration: number;
846
- /**
847
- * The time it takes Vitest to setup test harness (runner, mocks, etc.).
848
- */
849
- prepareDuration: number;
850
- /**
851
- * The time it takes to import the test module.
852
- * This includes importing everything in the module and executing suite callbacks.
853
- */
854
- collectDuration: number;
855
- /**
856
- * The time it takes to import the setup module.
857
- */
858
- setupDuration: number;
859
- /**
860
- * Accumulated duration of all tests and hooks in the module.
861
- */
862
- duration: number;
442
+ type Callback<Args extends Array<any> = []> = (...args: Args) => Awaitable<void>;
443
+ declare class Typechecker {
444
+ protected ctx: TestProject;
445
+ private _onParseStart?;
446
+ private _onParseEnd?;
447
+ private _onWatcherRerun?;
448
+ private _result;
449
+ private _startTime;
450
+ private _output;
451
+ private _tests;
452
+ private tempConfigPath?;
453
+ private allowJs?;
454
+ private process?;
455
+ protected files: string[];
456
+ constructor(ctx: TestProject);
457
+ setFiles(files: string[]): void;
458
+ onParseStart(fn: Callback): void;
459
+ onParseEnd(fn: Callback<[TypecheckResults]>): void;
460
+ onWatcherRerun(fn: Callback): void;
461
+ protected collectFileTests(filepath: string): Promise<FileInformation | null>;
462
+ protected getFiles(): string[];
463
+ collectTests(): Promise<Record<string, FileInformation>>;
464
+ protected markPassed(file: File): void;
465
+ protected prepareResults(output: string): Promise<{
466
+ files: File[];
467
+ sourceErrors: TypeCheckError[];
468
+ time: number;
469
+ }>;
470
+ protected parseTscLikeOutput(output: string): Promise<Map<string, {
471
+ error: TypeCheckError;
472
+ originalError: TscErrorInfo;
473
+ }[]>>;
474
+ clear(): Promise<void>;
475
+ stop(): Promise<void>;
476
+ protected ensurePackageInstalled(ctx: Vitest, checker: string): Promise<void>;
477
+ prepare(): Promise<void>;
478
+ getExitCode(): number | false;
479
+ getOutput(): string;
480
+ start(): Promise<void>;
481
+ getResult(): TypecheckResults;
482
+ getTestFiles(): File[];
483
+ getTestPacks(): TaskResultPack[];
863
484
  }
864
485
 
865
- declare class BasicReporter extends BaseReporter {
866
- constructor();
867
- reportSummary(files: File[], errors: unknown[]): void;
486
+ interface PrintErrorResult {
487
+ nearest?: ParsedStack;
868
488
  }
869
489
 
870
- interface ListRendererOptions {
871
- renderSucceed?: boolean;
872
- logger: Logger;
873
- showHeap: boolean;
874
- slowTestThreshold: number;
875
- mode: VitestRunMode;
490
+ interface Options {
491
+ /**
492
+ Show the cursor. This can be useful when a CLI accepts input from a user.
493
+
494
+ @example
495
+ ```
496
+ import {createLogUpdate} from 'log-update';
497
+
498
+ // Write output but don't hide the cursor
499
+ const log = createLogUpdate(process.stdout, {
500
+ showCursor: true
501
+ });
502
+ ```
503
+ */
504
+ readonly showCursor?: boolean;
876
505
  }
877
- declare function createListRenderer(_tasks: Task[], options: ListRendererOptions): {
878
- start(): any;
879
- update(_tasks: Task[]): any;
880
- stop(): any;
881
- clear(): void;
506
+
507
+ type LogUpdateMethods = {
508
+ /**
509
+ Clear the logged output.
510
+ */
511
+ clear(): void;
512
+
513
+ /**
514
+ Persist the logged output. Useful if you want to start a new log session below the current one.
515
+ */
516
+ done(): void;
882
517
  };
883
518
 
884
- declare class DefaultReporter extends BaseReporter {
885
- renderer?: ReturnType<typeof createListRenderer>;
886
- rendererOptions: ListRendererOptions;
887
- private renderSucceedDefault?;
888
- onPathsCollected(paths?: string[]): void;
889
- onTestRemoved(trigger?: string): Promise<void>;
890
- onCollected(): void;
891
- onFinished(files?: _vitest_runner.File[], errors?: unknown[]): void;
892
- onWatcherStart(files?: _vitest_runner.File[], errors?: unknown[]): Promise<void>;
893
- stopListRender(): void;
894
- onWatcherRerun(files: string[], trigger?: string): Promise<void>;
895
- onUserConsoleLog(log: UserConsoleLog): void;
519
+ /**
520
+ Log to `stdout` by overwriting the previous output in the terminal.
521
+
522
+ @param text - The text to log to `stdout`.
523
+
524
+ @example
525
+ ```
526
+ import logUpdate from 'log-update';
527
+
528
+ const frames = ['-', '\\', '|', '/'];
529
+ let index = 0;
530
+
531
+ setInterval(() => {
532
+ const frame = frames[index = ++index % frames.length];
533
+
534
+ logUpdate(
535
+ `
536
+ ♥♥
537
+ ${frame} unicorns ${frame}
538
+ ♥♥
539
+ `
540
+ );
541
+ }, 80);
542
+ ```
543
+ */
544
+ declare const logUpdate: ((...text: string[]) => void) & LogUpdateMethods;
545
+
546
+
547
+ /**
548
+ Get a `logUpdate` method that logs to the specified stream.
549
+
550
+ @param stream - The stream to log to.
551
+
552
+ @example
553
+ ```
554
+ import {createLogUpdate} from 'log-update';
555
+
556
+ // Write output but don't hide the cursor
557
+ const log = createLogUpdate(process.stdout);
558
+ ```
559
+ */
560
+ declare function createLogUpdate(
561
+ stream: NodeJS.WritableStream,
562
+ options?: Options
563
+ ): typeof logUpdate;
564
+
565
+ interface ErrorOptions {
566
+ type?: string;
567
+ fullStack?: boolean;
568
+ project?: TestProject;
569
+ verbose?: boolean;
570
+ screenshotPaths?: string[];
571
+ task?: Task;
572
+ showCodeFrame?: boolean;
573
+ }
574
+ declare class Logger {
575
+ ctx: Vitest;
576
+ outputStream: NodeJS.WriteStream | Writable;
577
+ errorStream: NodeJS.WriteStream | Writable;
578
+ logUpdate: ReturnType<typeof createLogUpdate>;
579
+ private _clearScreenPending;
580
+ private _highlights;
581
+ console: Console;
582
+ constructor(ctx: Vitest, outputStream?: NodeJS.WriteStream | Writable, errorStream?: NodeJS.WriteStream | Writable);
583
+ log(...args: any[]): void;
584
+ error(...args: any[]): void;
585
+ warn(...args: any[]): void;
586
+ clearFullScreen(message?: string): void;
587
+ clearScreen(message: string, force?: boolean): void;
588
+ private _clearScreen;
589
+ printError(err: unknown, options?: ErrorOptions): PrintErrorResult | undefined;
590
+ clearHighlightCache(filename?: string): void;
591
+ highlight(filename: string, source: string): string;
592
+ printNoTestFound(filters?: string[]): void;
593
+ printBanner(): void;
594
+ printBrowserBanner(project: TestProject): void;
595
+ printUnhandledErrors(errors: unknown[]): void;
596
+ printSourceTypeErrors(errors: TypeCheckError[]): void;
597
+ private registerUnhandledRejection;
896
598
  }
897
599
 
898
600
  interface DotRendererOptions {
@@ -907,6 +609,7 @@ declare function createDotRenderer(_tasks: Task[], options: DotRendererOptions):
907
609
 
908
610
  declare class DotReporter extends BaseReporter {
909
611
  renderer?: ReturnType<typeof createDotRenderer>;
612
+ onTaskUpdate(): void;
910
613
  onCollected(): void;
911
614
  onFinished(files?: _vitest_runner.File[], errors?: unknown[]): Promise<void>;
912
615
  onWatcherStart(): Promise<void>;
@@ -921,10 +624,114 @@ declare class GithubActionsReporter implements Reporter {
921
624
  onFinished(files?: File[], errors?: unknown[]): void;
922
625
  }
923
626
 
924
- declare class HangingProcessReporter implements Reporter {
925
- whyRunning: (() => void) | undefined;
926
- onInit(): void;
927
- onProcessTimeout(): void;
627
+ declare class HangingProcessReporter implements Reporter {
628
+ whyRunning: (() => void) | undefined;
629
+ onInit(): void;
630
+ onProcessTimeout(): void;
631
+ }
632
+
633
+ interface CoverageSummaryData {
634
+ lines: Totals;
635
+ statements: Totals;
636
+ branches: Totals;
637
+ functions: Totals;
638
+ }
639
+
640
+ declare class CoverageSummary {
641
+ constructor(data: CoverageSummary | CoverageSummaryData);
642
+ merge(obj: CoverageSummary): CoverageSummary;
643
+ toJSON(): CoverageSummaryData;
644
+ isEmpty(): boolean;
645
+ data: CoverageSummaryData;
646
+ lines: Totals;
647
+ statements: Totals;
648
+ branches: Totals;
649
+ functions: Totals;
650
+ }
651
+
652
+ interface CoverageMapData {
653
+ [key: string]: FileCoverage | FileCoverageData;
654
+ }
655
+
656
+ declare class CoverageMap {
657
+ constructor(data: CoverageMapData | CoverageMap);
658
+ addFileCoverage(pathOrObject: string | FileCoverage | FileCoverageData): void;
659
+ files(): string[];
660
+ fileCoverageFor(filename: string): FileCoverage;
661
+ filter(callback: (key: string) => boolean): void;
662
+ getCoverageSummary(): CoverageSummary;
663
+ merge(data: CoverageMapData | CoverageMap): void;
664
+ toJSON(): CoverageMapData;
665
+ data: CoverageMapData;
666
+ }
667
+
668
+ interface Location {
669
+ line: number;
670
+ column: number;
671
+ }
672
+
673
+ interface Range {
674
+ start: Location;
675
+ end: Location;
676
+ }
677
+
678
+ interface BranchMapping {
679
+ loc: Range;
680
+ type: string;
681
+ locations: Range[];
682
+ line: number;
683
+ }
684
+
685
+ interface FunctionMapping {
686
+ name: string;
687
+ decl: Range;
688
+ loc: Range;
689
+ line: number;
690
+ }
691
+
692
+ interface FileCoverageData {
693
+ path: string;
694
+ statementMap: { [key: string]: Range };
695
+ fnMap: { [key: string]: FunctionMapping };
696
+ branchMap: { [key: string]: BranchMapping };
697
+ s: { [key: string]: number };
698
+ f: { [key: string]: number };
699
+ b: { [key: string]: number[] };
700
+ }
701
+
702
+ interface Totals {
703
+ total: number;
704
+ covered: number;
705
+ skipped: number;
706
+ pct: number;
707
+ }
708
+
709
+ interface Coverage {
710
+ covered: number;
711
+ total: number;
712
+ coverage: number;
713
+ }
714
+
715
+ declare class FileCoverage implements FileCoverageData {
716
+ constructor(data: string | FileCoverage | FileCoverageData);
717
+ merge(other: FileCoverageData): void;
718
+ getBranchCoverageByLine(): { [line: number]: Coverage };
719
+ getLineCoverage(): { [line: number]: number };
720
+ getUncoveredLines(): number[];
721
+ resetHits(): void;
722
+ computeBranchTotals(): Totals;
723
+ computeSimpleTotals(): Totals;
724
+ toSummary(): CoverageSummary;
725
+ toJSON(): object;
726
+
727
+ data: FileCoverageData;
728
+ path: string;
729
+ statementMap: { [key: string]: Range };
730
+ fnMap: { [key: string]: FunctionMapping };
731
+ branchMap: { [key: string]: BranchMapping };
732
+ s: { [key: string]: number };
733
+ f: { [key: string]: number };
734
+ b: { [key: string]: number[] };
928
735
  }
929
736
 
930
737
  type Status = 'passed' | 'failed' | 'skipped' | 'pending' | 'todo' | 'disabled';
@@ -965,6 +772,7 @@ interface JsonTestResults {
965
772
  success: boolean;
966
773
  testResults: Array<JsonTestResult>;
967
774
  snapshot: SnapshotSummary;
775
+ coverageMap?: CoverageMap | null | undefined;
968
776
  }
969
777
  interface JsonOptions$1 {
970
778
  outputFile?: string;
@@ -975,8 +783,8 @@ declare class JsonReporter implements Reporter {
975
783
  options: JsonOptions$1;
976
784
  constructor(options: JsonOptions$1);
977
785
  onInit(ctx: Vitest): void;
978
- protected logTasks(files: File[]): Promise<void>;
979
- onFinished(files?: File[]): Promise<void>;
786
+ protected logTasks(files: File[], coverageMap?: CoverageMap | null): Promise<void>;
787
+ onFinished(files?: File[], _errors?: unknown[], coverageMap?: unknown): Promise<void>;
980
788
  /**
981
789
  * Writes the report to an output file if specified in the config,
982
790
  * or logs it to the console otherwise.
@@ -985,9 +793,18 @@ declare class JsonReporter implements Reporter {
985
793
  writeReport(report: string): Promise<void>;
986
794
  }
987
795
 
796
+ interface ClassnameTemplateVariables {
797
+ filename: string;
798
+ filepath: string;
799
+ }
988
800
  interface JUnitOptions {
989
801
  outputFile?: string;
802
+ /** @deprecated Use `classnameTemplate` instead. */
990
803
  classname?: string;
804
+ /**
805
+ * Template for the classname attribute. Can be either a string or a function. The string can contain placeholders {filename} and {filepath}.
806
+ */
807
+ classnameTemplate?: string | ((classnameVariables: ClassnameTemplateVariables) => string);
991
808
  suiteName?: string;
992
809
  /**
993
810
  * Write <system-out> and <system-err> for console output
@@ -1033,7 +850,7 @@ declare class TapFlatReporter extends TapReporter {
1033
850
 
1034
851
  declare class VerboseReporter extends DefaultReporter {
1035
852
  protected verbose: boolean;
1036
- constructor();
853
+ renderSucceed: boolean;
1037
854
  onTaskUpdate(packs: TaskResultPack[]): void;
1038
855
  }
1039
856
 
@@ -1101,9 +918,9 @@ declare const ReportersMap: {
1101
918
  };
1102
919
  type BuiltinReporters = keyof typeof ReportersMap;
1103
920
  interface BuiltinReporterOptions {
1104
- 'default': BaseOptions;
921
+ 'default': DefaultReporterOptions;
1105
922
  'basic': BaseOptions;
1106
- 'verbose': never;
923
+ 'verbose': DefaultReporterOptions;
1107
924
  'dot': BaseOptions;
1108
925
  'json': JsonOptions$1;
1109
926
  'blob': BlobOptions;
@@ -1114,6 +931,8 @@ interface BuiltinReporterOptions {
1114
931
  'html': HTMLOptions;
1115
932
  }
1116
933
 
934
+ type ChaiConfig = Omit<Partial<typeof chai.config>, 'useProxy' | 'proxyExcludedKeys'>;
935
+
1117
936
  interface TestSequencer {
1118
937
  /**
1119
938
  * Slicing tests into shards. Will be run before `sort`.
@@ -1764,6 +1583,10 @@ interface DepsOptions {
1764
1583
  type InlineReporter = Reporter;
1765
1584
  type ReporterName = BuiltinReporters | 'html' | (string & {});
1766
1585
  type ReporterWithOptions<Name extends ReporterName = ReporterName> = Name extends keyof BuiltinReporterOptions ? BuiltinReporterOptions[Name] extends never ? [Name, object] : [Name, Partial<BuiltinReporterOptions[Name]>] : [Name, Record<string, unknown>];
1586
+ interface ResolveSnapshotPathHandlerContext {
1587
+ config: SerializedConfig;
1588
+ }
1589
+ type ResolveSnapshotPathHandler = (testPath: string, snapExtension: string, context: ResolveSnapshotPathHandlerContext) => string;
1767
1590
  interface InlineConfig {
1768
1591
  /**
1769
1592
  * Name of the project. Will be used to display in the reporter.
@@ -1787,749 +1610,1073 @@ interface InlineConfig {
1787
1610
  */
1788
1611
  exclude?: string[];
1789
1612
  /**
1790
- * Include globs for in-source test files
1613
+ * Include globs for in-source test files
1614
+ *
1615
+ * @default []
1616
+ */
1617
+ includeSource?: string[];
1618
+ /**
1619
+ * Handling for dependencies inlining or externalizing
1620
+ *
1621
+ */
1622
+ deps?: DepsOptions;
1623
+ /**
1624
+ * Vite-node server options
1625
+ */
1626
+ server?: Omit<ViteNodeServerOptions, 'transformMode'>;
1627
+ /**
1628
+ * Base directory to scan for the test files
1629
+ *
1630
+ * @default `config.root`
1631
+ */
1632
+ dir?: string;
1633
+ /**
1634
+ * Register apis globally
1635
+ *
1636
+ * @default false
1637
+ */
1638
+ globals?: boolean;
1639
+ /**
1640
+ * Running environment
1641
+ *
1642
+ * Supports 'node', 'jsdom', 'happy-dom', 'edge-runtime'
1643
+ *
1644
+ * If used unsupported string, will try to load the package `vitest-environment-${env}`
1645
+ *
1646
+ * @default 'node'
1647
+ */
1648
+ environment?: VitestEnvironment;
1649
+ /**
1650
+ * Environment options.
1651
+ */
1652
+ environmentOptions?: EnvironmentOptions;
1653
+ /**
1654
+ * Automatically assign environment based on globs. The first match will be used.
1655
+ * This has effect only when running tests inside Node.js.
1656
+ *
1657
+ * Format: [glob, environment-name]
1658
+ *
1659
+ * @default []
1660
+ * @example [
1661
+ * // all tests in tests/dom will run in jsdom
1662
+ * ['tests/dom/**', 'jsdom'],
1663
+ * // all tests in tests/ with .edge.test.ts will run in edge-runtime
1664
+ * ['**\/*.edge.test.ts', 'edge-runtime'],
1665
+ * // ...
1666
+ * ]
1667
+ */
1668
+ environmentMatchGlobs?: [string, VitestEnvironment][];
1669
+ /**
1670
+ * Run tests in an isolated environment. This option has no effect on vmThreads pool.
1671
+ *
1672
+ * Disabling this option might improve performance if your code doesn't rely on side effects.
1673
+ *
1674
+ * @default true
1675
+ */
1676
+ isolate?: boolean;
1677
+ /**
1678
+ * Pool used to run tests in.
1679
+ *
1680
+ * Supports 'threads', 'forks', 'vmThreads'
1681
+ *
1682
+ * @default 'forks'
1683
+ */
1684
+ pool?: Exclude<Pool, 'browser'>;
1685
+ /**
1686
+ * Pool options
1687
+ */
1688
+ poolOptions?: PoolOptions;
1689
+ /**
1690
+ * Maximum number or percentage of workers to run tests in. `poolOptions.{threads,vmThreads}.maxThreads`/`poolOptions.forks.maxForks` has higher priority.
1691
+ */
1692
+ maxWorkers?: number | string;
1693
+ /**
1694
+ * Minimum number or percentage of workers to run tests in. `poolOptions.{threads,vmThreads}.minThreads`/`poolOptions.forks.minForks` has higher priority.
1695
+ */
1696
+ minWorkers?: number | string;
1697
+ /**
1698
+ * Should all test files run in parallel. Doesn't affect tests running in the same file.
1699
+ * Setting this to `false` will override `maxWorkers` and `minWorkers` options to `1`.
1700
+ *
1701
+ * @default true
1702
+ */
1703
+ fileParallelism?: boolean;
1704
+ /**
1705
+ * Automatically assign pool based on globs. The first match will be used.
1706
+ *
1707
+ * Format: [glob, pool-name]
1708
+ *
1709
+ * @default []
1710
+ * @example [
1711
+ * // all tests in "forks" directory will run using "poolOptions.forks" API
1712
+ * ['tests/forks/**', 'forks'],
1713
+ * // all other tests will run based on "poolOptions.threads" option, if you didn't specify other globs
1714
+ * // ...
1715
+ * ]
1716
+ */
1717
+ poolMatchGlobs?: [string, Exclude<Pool, 'browser'>][];
1718
+ /**
1719
+ * Path to a workspace configuration file
1720
+ */
1721
+ workspace?: string;
1722
+ /**
1723
+ * Update snapshot
1724
+ *
1725
+ * @default false
1726
+ */
1727
+ update?: boolean;
1728
+ /**
1729
+ * Watch mode
1730
+ *
1731
+ * @default !process.env.CI
1732
+ */
1733
+ watch?: boolean;
1734
+ /**
1735
+ * Project root
1736
+ *
1737
+ * @default process.cwd()
1738
+ */
1739
+ root?: string;
1740
+ /**
1741
+ * Custom reporter for output. Can contain one or more built-in report names, reporter instances,
1742
+ * and/or paths to custom reporters.
1743
+ *
1744
+ * @default []
1745
+ */
1746
+ reporters?: Arrayable$1<ReporterName | InlineReporter> | ((ReporterName | InlineReporter) | [ReporterName] | ReporterWithOptions)[];
1747
+ /**
1748
+ * Write test results to a file when the --reporter=json` or `--reporter=junit` option is also specified.
1749
+ * Also definable individually per reporter by using an object instead.
1750
+ */
1751
+ outputFile?: string | (Partial<Record<BuiltinReporters, string>> & Record<string, string>);
1752
+ /**
1753
+ * Default timeout of a test in milliseconds
1754
+ *
1755
+ * @default 5000
1756
+ */
1757
+ testTimeout?: number;
1758
+ /**
1759
+ * Default timeout of a hook in milliseconds
1760
+ *
1761
+ * @default 10000
1762
+ */
1763
+ hookTimeout?: number;
1764
+ /**
1765
+ * Default timeout to wait for close when Vitest shuts down, in milliseconds
1766
+ *
1767
+ * @default 10000
1768
+ */
1769
+ teardownTimeout?: number;
1770
+ /**
1771
+ * Silent mode
1772
+ *
1773
+ * @default false
1774
+ */
1775
+ silent?: boolean;
1776
+ /**
1777
+ * Hide logs for skipped tests
1778
+ *
1779
+ * @default false
1780
+ */
1781
+ hideSkippedTests?: boolean;
1782
+ /**
1783
+ * Path to setup files
1784
+ */
1785
+ setupFiles?: string | string[];
1786
+ /**
1787
+ * Path to global setup files
1788
+ */
1789
+ globalSetup?: string | string[];
1790
+ /**
1791
+ * Glob patter of file paths that will trigger the whole suite rerun
1792
+ *
1793
+ * Useful if you are testing calling CLI commands
1794
+ *
1795
+ * @default ['**\/package.json/**', '**\/{vitest,vite}.config.*\/**']
1796
+ */
1797
+ forceRerunTriggers?: string[];
1798
+ /**
1799
+ * Coverage options
1800
+ */
1801
+ coverage?: CoverageOptions;
1802
+ /**
1803
+ * run test names with the specified pattern
1804
+ */
1805
+ testNamePattern?: string | RegExp;
1806
+ /**
1807
+ * Will call `.mockClear()` on all spies before each test
1808
+ * @default false
1809
+ */
1810
+ clearMocks?: boolean;
1811
+ /**
1812
+ * Will call `.mockReset()` on all spies before each test
1813
+ * @default false
1814
+ */
1815
+ mockReset?: boolean;
1816
+ /**
1817
+ * Will call `.mockRestore()` on all spies before each test
1818
+ * @default false
1819
+ */
1820
+ restoreMocks?: boolean;
1821
+ /**
1822
+ * Will restore all global stubs to their original values before each test
1823
+ * @default false
1824
+ */
1825
+ unstubGlobals?: boolean;
1826
+ /**
1827
+ * Will restore all env stubs to their original values before each test
1828
+ * @default false
1829
+ */
1830
+ unstubEnvs?: boolean;
1831
+ /**
1832
+ * Serve API options.
1833
+ *
1834
+ * When set to true, the default port is 51204.
1835
+ *
1836
+ * @default false
1837
+ */
1838
+ api?: boolean | number | ApiConfig;
1839
+ /**
1840
+ * Enable Vitest UI
1841
+ *
1842
+ * @default false
1843
+ */
1844
+ ui?: boolean;
1845
+ /**
1846
+ * options for test in a browser environment
1847
+ * @experimental
1848
+ *
1849
+ * @default false
1850
+ */
1851
+ browser?: BrowserConfigOptions;
1852
+ /**
1853
+ * Open UI automatically.
1791
1854
  *
1792
- * @default []
1855
+ * @default !process.env.CI
1793
1856
  */
1794
- includeSource?: string[];
1857
+ open?: boolean;
1795
1858
  /**
1796
- * Handling for dependencies inlining or externalizing
1859
+ * Base url for the UI
1797
1860
  *
1861
+ * @default '/__vitest__/'
1798
1862
  */
1799
- deps?: DepsOptions;
1863
+ uiBase?: string;
1800
1864
  /**
1801
- * Vite-node server options
1865
+ * Determine the transform method for all modules imported inside a test that matches the glob pattern.
1802
1866
  */
1803
- server?: Omit<ViteNodeServerOptions, 'transformMode'>;
1867
+ testTransformMode?: TransformModePatterns;
1804
1868
  /**
1805
- * Base directory to scan for the test files
1806
- *
1807
- * @default `config.root`
1869
+ * Format options for snapshot testing.
1808
1870
  */
1809
- dir?: string;
1871
+ snapshotFormat?: Omit<PrettyFormatOptions, 'plugins'>;
1810
1872
  /**
1811
- * Register apis globally
1812
- *
1813
- * @default false
1873
+ * Path to a module which has a default export of diff config.
1814
1874
  */
1815
- globals?: boolean;
1875
+ diff?: string | SerializedDiffOptions;
1816
1876
  /**
1817
- * Running environment
1818
- *
1819
- * Supports 'node', 'jsdom', 'happy-dom', 'edge-runtime'
1820
- *
1821
- * If used unsupported string, will try to load the package `vitest-environment-${env}`
1822
- *
1823
- * @default 'node'
1877
+ * Paths to snapshot serializer modules.
1824
1878
  */
1825
- environment?: VitestEnvironment;
1879
+ snapshotSerializers?: string[];
1826
1880
  /**
1827
- * Environment options.
1881
+ * Resolve custom snapshot path
1828
1882
  */
1829
- environmentOptions?: EnvironmentOptions;
1883
+ resolveSnapshotPath?: ResolveSnapshotPathHandler;
1830
1884
  /**
1831
- * Automatically assign environment based on globs. The first match will be used.
1832
- * This has effect only when running tests inside Node.js.
1833
- *
1834
- * Format: [glob, environment-name]
1835
- *
1836
- * @default []
1837
- * @example [
1838
- * // all tests in tests/dom will run in jsdom
1839
- * ['tests/dom/**', 'jsdom'],
1840
- * // all tests in tests/ with .edge.test.ts will run in edge-runtime
1841
- * ['**\/*.edge.test.ts', 'edge-runtime'],
1842
- * // ...
1843
- * ]
1885
+ * Path to a custom snapshot environment module that has a default export of `SnapshotEnvironment` object.
1844
1886
  */
1845
- environmentMatchGlobs?: [string, VitestEnvironment][];
1887
+ snapshotEnvironment?: string;
1846
1888
  /**
1847
- * Run tests in an isolated environment. This option has no effect on vmThreads pool.
1848
- *
1849
- * Disabling this option might improve performance if your code doesn't rely on side effects.
1850
- *
1851
- * @default true
1889
+ * Pass with no tests
1852
1890
  */
1853
- isolate?: boolean;
1891
+ passWithNoTests?: boolean;
1854
1892
  /**
1855
- * Pool used to run tests in.
1856
- *
1857
- * Supports 'threads', 'forks', 'vmThreads'
1893
+ * Allow tests and suites that are marked as only
1858
1894
  *
1859
- * @default 'forks'
1895
+ * @default !process.env.CI
1860
1896
  */
1861
- pool?: Exclude<Pool, 'browser'>;
1897
+ allowOnly?: boolean;
1862
1898
  /**
1863
- * Pool options
1899
+ * Show heap usage after each test. Useful for debugging memory leaks.
1864
1900
  */
1865
- poolOptions?: PoolOptions;
1901
+ logHeapUsage?: boolean;
1866
1902
  /**
1867
- * Maximum number or percentage of workers to run tests in. `poolOptions.{threads,vmThreads}.maxThreads`/`poolOptions.forks.maxForks` has higher priority.
1903
+ * Custom environment variables assigned to `process.env` before running tests.
1868
1904
  */
1869
- maxWorkers?: number | string;
1905
+ env?: Partial<NodeJS.ProcessEnv>;
1870
1906
  /**
1871
- * Minimum number or percentage of workers to run tests in. `poolOptions.{threads,vmThreads}.minThreads`/`poolOptions.forks.minForks` has higher priority.
1907
+ * Options for @sinon/fake-timers
1872
1908
  */
1873
- minWorkers?: number | string;
1909
+ fakeTimers?: FakeTimerInstallOpts;
1874
1910
  /**
1875
- * Should all test files run in parallel. Doesn't affect tests running in the same file.
1876
- * Setting this to `false` will override `maxWorkers` and `minWorkers` options to `1`.
1911
+ * Custom handler for console.log in tests.
1877
1912
  *
1878
- * @default true
1913
+ * Return `false` to ignore the log.
1879
1914
  */
1880
- fileParallelism?: boolean;
1915
+ onConsoleLog?: (log: string, type: 'stdout' | 'stderr') => boolean | void;
1881
1916
  /**
1882
- * Automatically assign pool based on globs. The first match will be used.
1917
+ * Enable stack trace filtering. If absent, all stack trace frames
1918
+ * will be shown.
1883
1919
  *
1884
- * Format: [glob, pool-name]
1920
+ * Return `false` to omit the frame.
1921
+ */
1922
+ onStackTrace?: (error: ErrorWithDiff, frame: ParsedStack) => boolean | void;
1923
+ /**
1924
+ * Indicates if CSS files should be processed.
1885
1925
  *
1886
- * @default []
1887
- * @example [
1888
- * // all tests in "forks" directory will run using "poolOptions.forks" API
1889
- * ['tests/forks/**', 'forks'],
1890
- * // all other tests will run based on "poolOptions.threads" option, if you didn't specify other globs
1891
- * // ...
1892
- * ]
1926
+ * When excluded, the CSS files will be replaced with empty strings to bypass the subsequent processing.
1927
+ *
1928
+ * @default { include: [], modules: { classNameStrategy: false } }
1893
1929
  */
1894
- poolMatchGlobs?: [string, Exclude<Pool, 'browser'>][];
1930
+ css?: boolean | {
1931
+ include?: RegExp | RegExp[];
1932
+ exclude?: RegExp | RegExp[];
1933
+ modules?: {
1934
+ classNameStrategy?: CSSModuleScopeStrategy;
1935
+ };
1936
+ };
1895
1937
  /**
1896
- * Path to a workspace configuration file
1938
+ * A number of tests that are allowed to run at the same time marked with `test.concurrent`.
1939
+ * @default 5
1897
1940
  */
1898
- workspace?: string;
1941
+ maxConcurrency?: number;
1899
1942
  /**
1900
- * Update snapshot
1901
- *
1902
- * @default false
1943
+ * Options for configuring cache policy.
1944
+ * @default { dir: 'node_modules/.vite/vitest' }
1903
1945
  */
1904
- update?: boolean;
1946
+ cache?: false | {
1947
+ /**
1948
+ * @deprecated Use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest".
1949
+ */
1950
+ dir: string;
1951
+ };
1905
1952
  /**
1906
- * Watch mode
1907
- *
1908
- * @default !process.env.CI
1953
+ * Options for configuring the order of running tests.
1909
1954
  */
1910
- watch?: boolean;
1955
+ sequence?: SequenceOptions;
1911
1956
  /**
1912
- * Project root
1913
- *
1914
- * @default process.cwd()
1957
+ * Specifies an `Object`, or an `Array` of `Object`,
1958
+ * which defines aliases used to replace values in `import` or `require` statements.
1959
+ * Will be merged with the default aliases inside `resolve.alias`.
1915
1960
  */
1916
- root?: string;
1961
+ alias?: AliasOptions;
1917
1962
  /**
1918
- * Custom reporter for output. Can contain one or more built-in report names, reporter instances,
1919
- * and/or paths to custom reporters.
1963
+ * Ignore any unhandled errors that occur
1920
1964
  *
1921
- * @default []
1965
+ * @default false
1922
1966
  */
1923
- reporters?: Arrayable$1<ReporterName | InlineReporter> | ((ReporterName | InlineReporter) | [ReporterName] | ReporterWithOptions)[];
1967
+ dangerouslyIgnoreUnhandledErrors?: boolean;
1924
1968
  /**
1925
- * Write test results to a file when the --reporter=json` or `--reporter=junit` option is also specified.
1926
- * Also definable individually per reporter by using an object instead.
1969
+ * Options for configuring typechecking test environment.
1927
1970
  */
1928
- outputFile?: string | (Partial<Record<BuiltinReporters, string>> & Record<string, string>);
1971
+ typecheck?: Partial<TypecheckConfig>;
1929
1972
  /**
1930
- * Default timeout of a test in milliseconds
1973
+ * The number of milliseconds after which a test is considered slow and reported as such in the results.
1931
1974
  *
1932
- * @default 5000
1975
+ * @default 300
1933
1976
  */
1934
- testTimeout?: number;
1977
+ slowTestThreshold?: number;
1935
1978
  /**
1936
- * Default timeout of a hook in milliseconds
1937
- *
1938
- * @default 10000
1979
+ * Path to a custom test runner.
1939
1980
  */
1940
- hookTimeout?: number;
1981
+ runner?: string;
1941
1982
  /**
1942
- * Default timeout to wait for close when Vitest shuts down, in milliseconds
1983
+ * Debug tests by opening `node:inspector` in worker / child process.
1984
+ * Provides similar experience as `--inspect` Node CLI argument.
1943
1985
  *
1944
- * @default 10000
1986
+ * Requires `poolOptions.threads.singleThread: true` OR `poolOptions.forks.singleFork: true`.
1945
1987
  */
1946
- teardownTimeout?: number;
1988
+ inspect?: boolean | string;
1947
1989
  /**
1948
- * Silent mode
1990
+ * Debug tests by opening `node:inspector` in worker / child process and wait for debugger to connect.
1991
+ * Provides similar experience as `--inspect-brk` Node CLI argument.
1949
1992
  *
1950
- * @default false
1993
+ * Requires `poolOptions.threads.singleThread: true` OR `poolOptions.forks.singleFork: true`.
1951
1994
  */
1952
- silent?: boolean;
1995
+ inspectBrk?: boolean | string;
1953
1996
  /**
1954
- * Hide logs for skipped tests
1955
- *
1956
- * @default false
1997
+ * Inspector options. If `--inspect` or `--inspect-brk` is enabled, these options will be passed to the inspector.
1957
1998
  */
1958
- hideSkippedTests?: boolean;
1999
+ inspector?: {
2000
+ /**
2001
+ * Enable inspector
2002
+ */
2003
+ enabled?: boolean;
2004
+ /**
2005
+ * Port to run inspector on
2006
+ */
2007
+ port?: number;
2008
+ /**
2009
+ * Host to run inspector on
2010
+ */
2011
+ host?: string;
2012
+ /**
2013
+ * Wait for debugger to connect before running tests
2014
+ */
2015
+ waitForDebugger?: boolean;
2016
+ };
1959
2017
  /**
1960
- * Path to setup files
2018
+ * Define variables that will be returned from `inject` in the test environment.
2019
+ * @example
2020
+ * ```ts
2021
+ * // vitest.config.ts
2022
+ * export default defineConfig({
2023
+ * test: {
2024
+ * provide: {
2025
+ * someKey: 'someValue'
2026
+ * }
2027
+ * }
2028
+ * })
2029
+ * ```
2030
+ * ```ts
2031
+ * // test file
2032
+ * import { inject } from 'vitest'
2033
+ * const value = inject('someKey') // 'someValue'
2034
+ * ```
2035
+ */
2036
+ provide?: Partial<ProvidedContext>;
2037
+ /**
2038
+ * Configuration options for expect() matches.
2039
+ */
2040
+ expect?: {
2041
+ /**
2042
+ * Throw an error if tests don't have any expect() assertions.
2043
+ */
2044
+ requireAssertions?: boolean;
2045
+ /**
2046
+ * Default options for expect.poll()
2047
+ */
2048
+ poll?: {
2049
+ /**
2050
+ * Timeout in milliseconds
2051
+ * @default 1000
2052
+ */
2053
+ timeout?: number;
2054
+ /**
2055
+ * Polling interval in milliseconds
2056
+ * @default 50
2057
+ */
2058
+ interval?: number;
2059
+ };
2060
+ };
2061
+ /**
2062
+ * Modify default Chai config. Vitest uses Chai for `expect` and `assert` matches.
2063
+ * https://github.com/chaijs/chai/blob/4.x.x/lib/chai/config.js
1961
2064
  */
1962
- setupFiles?: string | string[];
2065
+ chaiConfig?: ChaiConfig;
1963
2066
  /**
1964
- * Path to global setup files
2067
+ * Stop test execution when given number of tests have failed.
1965
2068
  */
1966
- globalSetup?: string | string[];
2069
+ bail?: number;
1967
2070
  /**
1968
- * Glob patter of file paths that will trigger the whole suite rerun
1969
- *
1970
- * Useful if you are testing calling CLI commands
2071
+ * Retry the test specific number of times if it fails.
1971
2072
  *
1972
- * @default ['**\/package.json/**', '**\/{vitest,vite}.config.*\/**']
1973
- */
1974
- forceRerunTriggers?: string[];
1975
- /**
1976
- * Coverage options
2073
+ * @default 0
1977
2074
  */
1978
- coverage?: CoverageOptions;
2075
+ retry?: number;
1979
2076
  /**
1980
- * run test names with the specified pattern
2077
+ * Show full diff when snapshot fails instead of a patch.
1981
2078
  */
1982
- testNamePattern?: string | RegExp;
2079
+ expandSnapshotDiff?: boolean;
1983
2080
  /**
1984
- * Will call `.mockClear()` on all spies before each test
2081
+ * By default, Vitest automatically intercepts console logging during tests for extra formatting of test file, test title, etc...
2082
+ * This is also required for console log preview on Vitest UI.
2083
+ * However, disabling such interception might help when you want to debug a code with normal synchronus terminal console logging.
2084
+ *
2085
+ * This option has no effect on browser pool since Vitest preserves original logging on browser devtools.
2086
+ *
1985
2087
  * @default false
1986
2088
  */
1987
- clearMocks?: boolean;
2089
+ disableConsoleIntercept?: boolean;
1988
2090
  /**
1989
- * Will call `.mockReset()` on all spies before each test
2091
+ * Always print console stack traces.
2092
+ *
1990
2093
  * @default false
1991
2094
  */
1992
- mockReset?: boolean;
2095
+ printConsoleTrace?: boolean;
1993
2096
  /**
1994
- * Will call `.mockRestore()` on all spies before each test
2097
+ * Include "location" property inside the test definition
2098
+ *
1995
2099
  * @default false
1996
2100
  */
1997
- restoreMocks?: boolean;
2101
+ includeTaskLocation?: boolean;
2102
+ }
2103
+ interface TypecheckConfig {
1998
2104
  /**
1999
- * Will restore all global stubs to their original values before each test
2000
- * @default false
2105
+ * Run typechecking tests alongisde regular tests.
2001
2106
  */
2002
- unstubGlobals?: boolean;
2107
+ enabled?: boolean;
2003
2108
  /**
2004
- * Will restore all env stubs to their original values before each test
2005
- * @default false
2109
+ * When typechecking is enabled, only run typechecking tests.
2006
2110
  */
2007
- unstubEnvs?: boolean;
2111
+ only?: boolean;
2008
2112
  /**
2009
- * Serve API options.
2010
- *
2011
- * When set to true, the default port is 51204.
2113
+ * What tools to use for type checking.
2012
2114
  *
2013
- * @default false
2115
+ * @default 'tsc'
2014
2116
  */
2015
- api?: boolean | number | ApiConfig;
2117
+ checker: 'tsc' | 'vue-tsc' | (string & Record<never, never>);
2016
2118
  /**
2017
- * Enable Vitest UI
2119
+ * Pattern for files that should be treated as test files
2018
2120
  *
2019
- * @default false
2121
+ * @default ['**\/*.{test,spec}-d.?(c|m)[jt]s?(x)']
2020
2122
  */
2021
- ui?: boolean;
2123
+ include: string[];
2022
2124
  /**
2023
- * options for test in a browser environment
2024
- * @experimental
2125
+ * Pattern for files that should not be treated as test files
2025
2126
  *
2026
- * @default false
2127
+ * @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.*']
2027
2128
  */
2028
- browser?: BrowserConfigOptions;
2129
+ exclude: string[];
2029
2130
  /**
2030
- * Open UI automatically.
2031
- *
2032
- * @default !process.env.CI
2131
+ * Check JS files that have `@ts-check` comment.
2132
+ * If you have it enabled in tsconfig, this will not overwrite it.
2033
2133
  */
2034
- open?: boolean;
2134
+ allowJs?: boolean;
2035
2135
  /**
2036
- * Base url for the UI
2037
- *
2038
- * @default '/__vitest__/'
2136
+ * Do not fail, if Vitest found errors outside the test files.
2039
2137
  */
2040
- uiBase?: string;
2138
+ ignoreSourceErrors?: boolean;
2041
2139
  /**
2042
- * Determine the transform method for all modules imported inside a test that matches the glob pattern.
2140
+ * Path to tsconfig, relative to the project root.
2043
2141
  */
2044
- testTransformMode?: TransformModePatterns;
2142
+ tsconfig?: string;
2143
+ }
2144
+ interface UserConfig extends InlineConfig {
2045
2145
  /**
2046
- * Format options for snapshot testing.
2146
+ * Path to the config file.
2147
+ *
2148
+ * Default resolving to `vitest.config.*`, `vite.config.*`
2149
+ *
2150
+ * Setting to `false` will disable config resolving.
2047
2151
  */
2048
- snapshotFormat?: Omit<PrettyFormatOptions, 'plugins'>;
2152
+ config?: string | false | undefined;
2049
2153
  /**
2050
- * Path to a module which has a default export of diff config.
2154
+ * Do not run tests when Vitest starts.
2155
+ *
2156
+ * Vitest will only run tests if it's called programmatically or the test file changes.
2157
+ *
2158
+ * CLI file filters will be ignored.
2051
2159
  */
2052
- diff?: string;
2160
+ standalone?: boolean;
2053
2161
  /**
2054
- * Paths to snapshot serializer modules.
2162
+ * Use happy-dom
2055
2163
  */
2056
- snapshotSerializers?: string[];
2164
+ dom?: boolean;
2057
2165
  /**
2058
- * Resolve custom snapshot path
2166
+ * Run tests that cover a list of source files
2059
2167
  */
2060
- resolveSnapshotPath?: (path: string, extension: string) => string;
2168
+ related?: string[] | string;
2061
2169
  /**
2062
- * Path to a custom snapshot environment module that has a default export of `SnapshotEnvironment` object.
2170
+ * Overrides Vite mode
2171
+ * @default 'test'
2063
2172
  */
2064
- snapshotEnvironment?: string;
2173
+ mode?: string;
2065
2174
  /**
2066
- * Pass with no tests
2175
+ * Runs tests that are affected by the changes in the repository, or between specified branch or commit hash
2176
+ * Requires initialized git repository
2177
+ * @default false
2067
2178
  */
2068
- passWithNoTests?: boolean;
2179
+ changed?: boolean | string;
2069
2180
  /**
2070
- * Allow tests and suites that are marked as only
2071
- *
2072
- * @default !process.env.CI
2181
+ * Test suite shard to execute in a format of <index>/<count>.
2182
+ * Will divide tests into a `count` numbers, and run only the `indexed` part.
2183
+ * Cannot be used with enabled watch.
2184
+ * @example --shard=2/3
2073
2185
  */
2074
- allowOnly?: boolean;
2186
+ shard?: string;
2075
2187
  /**
2076
- * Show heap usage after each test. Useful for debugging memory leaks.
2188
+ * Name of the project or projects to run.
2077
2189
  */
2078
- logHeapUsage?: boolean;
2190
+ project?: string | string[];
2079
2191
  /**
2080
- * Custom environment variables assigned to `process.env` before running tests.
2192
+ * Additional exclude patterns
2081
2193
  */
2082
- env?: Partial<NodeJS.ProcessEnv>;
2194
+ cliExclude?: string[];
2083
2195
  /**
2084
- * Options for @sinon/fake-timers
2196
+ * Override vite config's clearScreen from cli
2085
2197
  */
2086
- fakeTimers?: FakeTimerInstallOpts;
2198
+ clearScreen?: boolean;
2087
2199
  /**
2088
- * Custom handler for console.log in tests.
2089
- *
2090
- * Return `false` to ignore the log.
2200
+ * benchmark.compare option exposed at the top level for cli
2091
2201
  */
2092
- onConsoleLog?: (log: string, type: 'stdout' | 'stderr') => boolean | void;
2202
+ compare?: string;
2093
2203
  /**
2094
- * Enable stack trace filtering. If absent, all stack trace frames
2095
- * will be shown.
2096
- *
2097
- * Return `false` to omit the frame.
2204
+ * benchmark.outputJson option exposed at the top level for cli
2098
2205
  */
2099
- onStackTrace?: (error: ErrorWithDiff, frame: ParsedStack) => boolean | void;
2206
+ outputJson?: string;
2100
2207
  /**
2101
- * Indicates if CSS files should be processed.
2102
- *
2103
- * When excluded, the CSS files will be replaced with empty strings to bypass the subsequent processing.
2104
- *
2105
- * @default { include: [], modules: { classNameStrategy: false } }
2208
+ * Directory of blob reports to merge
2209
+ * @default '.vitest-reports'
2106
2210
  */
2107
- css?: boolean | {
2108
- include?: RegExp | RegExp[];
2109
- exclude?: RegExp | RegExp[];
2110
- modules?: {
2111
- classNameStrategy?: CSSModuleScopeStrategy;
2112
- };
2211
+ mergeReports?: string;
2212
+ }
2213
+ interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'browser' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'benchmark' | 'shard' | 'cache' | 'sequence' | 'typecheck' | 'runner' | 'poolOptions' | 'pool' | 'cliExclude' | 'diff' | 'setupFiles' | 'snapshotEnvironment' | 'bail'> {
2214
+ mode: VitestRunMode;
2215
+ base?: string;
2216
+ diff?: string | SerializedDiffOptions;
2217
+ bail?: number;
2218
+ setupFiles: string[];
2219
+ snapshotEnvironment?: string;
2220
+ config?: string;
2221
+ filters?: string[];
2222
+ testNamePattern?: RegExp;
2223
+ related?: string[];
2224
+ coverage: ResolvedCoverageOptions;
2225
+ snapshotOptions: SnapshotStateOptions;
2226
+ browser: ResolvedBrowserOptions;
2227
+ pool: Pool;
2228
+ poolOptions?: ResolvedPoolOptions;
2229
+ reporters: (InlineReporter | ReporterWithOptions)[];
2230
+ defines: Record<string, any>;
2231
+ api?: ApiConfig;
2232
+ cliExclude?: string[];
2233
+ benchmark?: Required<Omit<BenchmarkUserOptions, 'outputFile' | 'compare' | 'outputJson'>> & Pick<BenchmarkUserOptions, 'outputFile' | 'compare' | 'outputJson'>;
2234
+ shard?: {
2235
+ index: number;
2236
+ count: number;
2237
+ };
2238
+ cache: {
2239
+ /**
2240
+ * @deprecated
2241
+ */
2242
+ dir: string;
2243
+ } | false;
2244
+ sequence: {
2245
+ sequencer: TestSequencerConstructor;
2246
+ hooks: SequenceHooks;
2247
+ setupFiles: SequenceSetupFiles;
2248
+ shuffle?: boolean;
2249
+ concurrent?: boolean;
2250
+ seed: number;
2251
+ };
2252
+ typecheck: Omit<TypecheckConfig, 'enabled'> & {
2253
+ enabled: boolean;
2254
+ };
2255
+ runner?: string;
2256
+ maxWorkers: number;
2257
+ minWorkers: number;
2258
+ }
2259
+ 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';
2260
+ type ProjectConfig = Omit<UserConfig, NonProjectOptions | 'sequencer' | 'deps' | 'poolOptions'> & {
2261
+ sequencer?: Omit<SequenceOptions, 'sequencer' | 'seed'>;
2262
+ deps?: Omit<DepsOptions, 'moduleDirectories'>;
2263
+ poolOptions?: {
2264
+ threads?: Pick<NonNullable<PoolOptions['threads']>, 'singleThread' | 'isolate'>;
2265
+ vmThreads?: Pick<NonNullable<PoolOptions['vmThreads']>, 'singleThread'>;
2266
+ forks?: Pick<NonNullable<PoolOptions['forks']>, 'singleFork' | 'isolate'>;
2113
2267
  };
2268
+ };
2269
+ type ResolvedProjectConfig = Omit<ResolvedConfig, Exclude<NonProjectOptions, 'coverage' | 'watch'>>;
2270
+ interface UserWorkspaceConfig extends UserConfig$1 {
2271
+ test?: ProjectConfig;
2272
+ }
2273
+ type UserProjectConfigFn = (env: ConfigEnv) => UserWorkspaceConfig | Promise<UserWorkspaceConfig>;
2274
+ type UserProjectConfigExport = UserWorkspaceConfig | Promise<UserWorkspaceConfig> | UserProjectConfigFn;
2275
+ type TestProjectConfiguration = string | (UserProjectConfigExport & {
2114
2276
  /**
2115
- * A number of tests that are allowed to run at the same time marked with `test.concurrent`.
2116
- * @default 5
2277
+ * Relative path to the extendable config. All other options will be merged with this config.
2278
+ * @example '../vite.config.ts'
2279
+ */
2280
+ extends?: string;
2281
+ });
2282
+ /** @deprecated use `TestProjectConfiguration` instead */
2283
+ type WorkspaceProjectConfiguration = TestProjectConfiguration;
2284
+
2285
+ interface BrowserProviderInitializationOptions {
2286
+ browser: string;
2287
+ options?: BrowserProviderOptions;
2288
+ }
2289
+ interface CDPSession {
2290
+ send: (method: string, params?: Record<string, unknown>) => Promise<unknown>;
2291
+ on: (event: string, listener: (...args: unknown[]) => void) => void;
2292
+ once: (event: string, listener: (...args: unknown[]) => void) => void;
2293
+ off: (event: string, listener: (...args: unknown[]) => void) => void;
2294
+ }
2295
+ interface BrowserProvider {
2296
+ name: string;
2297
+ /**
2298
+ * @experimental opt-in into file parallelisation
2117
2299
  */
2118
- maxConcurrency?: number;
2300
+ supportsParallelism: boolean;
2301
+ getSupportedBrowsers: () => readonly string[];
2302
+ beforeCommand?: (command: string, args: unknown[]) => Awaitable$1<void>;
2303
+ afterCommand?: (command: string, args: unknown[]) => Awaitable$1<void>;
2304
+ getCommandsContext: (contextId: string) => Record<string, unknown>;
2305
+ openPage: (contextId: string, url: string, beforeNavigate?: () => Promise<void>) => Promise<void>;
2306
+ getCDPSession?: (contextId: string) => Promise<CDPSession>;
2307
+ close: () => Awaitable$1<void>;
2308
+ initialize(ctx: TestProject, options: BrowserProviderInitializationOptions): Awaitable$1<void>;
2309
+ }
2310
+ interface BrowserProviderModule {
2311
+ new (): BrowserProvider;
2312
+ }
2313
+ interface BrowserProviderOptions {
2314
+ }
2315
+ type BrowserBuiltinProvider = 'webdriverio' | 'playwright' | 'preview';
2316
+ interface BrowserConfigOptions {
2119
2317
  /**
2120
- * Options for configuring cache policy.
2121
- * @default { dir: 'node_modules/.vite/vitest' }
2318
+ * if running tests in the browser should be the default
2319
+ *
2320
+ * @default false
2122
2321
  */
2123
- cache?: false | {
2124
- /**
2125
- * @deprecated Use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest".
2126
- */
2127
- dir: string;
2128
- };
2322
+ enabled?: boolean;
2129
2323
  /**
2130
- * Options for configuring the order of running tests.
2324
+ * Name of the browser
2131
2325
  */
2132
- sequence?: SequenceOptions;
2326
+ name: string;
2133
2327
  /**
2134
- * Specifies an `Object`, or an `Array` of `Object`,
2135
- * which defines aliases used to replace values in `import` or `require` statements.
2136
- * Will be merged with the default aliases inside `resolve.alias`.
2328
+ * Browser provider
2329
+ *
2330
+ * @default 'preview'
2137
2331
  */
2138
- alias?: AliasOptions;
2332
+ provider?: BrowserBuiltinProvider | (string & {});
2139
2333
  /**
2140
- * Ignore any unhandled errors that occur
2334
+ * Options that are passed down to a browser provider.
2335
+ * To support type hinting, add one of the types to your tsconfig.json "compilerOptions.types" field:
2141
2336
  *
2142
- * @default false
2337
+ * - for webdriverio: `@vitest/browser/providers/webdriverio`
2338
+ * - for playwright: `@vitest/browser/providers/playwright`
2339
+ *
2340
+ * @example
2341
+ * { playwright: { launch: { devtools: true } }
2143
2342
  */
2144
- dangerouslyIgnoreUnhandledErrors?: boolean;
2343
+ providerOptions?: BrowserProviderOptions;
2145
2344
  /**
2146
- * Options for configuring typechecking test environment.
2345
+ * enable headless mode
2346
+ *
2347
+ * @default process.env.CI
2147
2348
  */
2148
- typecheck?: Partial<TypecheckConfig>;
2349
+ headless?: boolean;
2149
2350
  /**
2150
- * The number of milliseconds after which a test is considered slow and reported as such in the results.
2351
+ * Serve API options.
2151
2352
  *
2152
- * @default 300
2353
+ * The default port is 63315.
2153
2354
  */
2154
- slowTestThreshold?: number;
2355
+ api?: ApiConfig | number;
2155
2356
  /**
2156
- * Path to a custom test runner.
2357
+ * Isolate test environment after each test
2358
+ *
2359
+ * @default true
2157
2360
  */
2158
- runner?: string;
2361
+ isolate?: boolean;
2159
2362
  /**
2160
- * Debug tests by opening `node:inspector` in worker / child process.
2161
- * Provides similar experience as `--inspect` Node CLI argument.
2363
+ * Run test files in parallel if provider supports this option
2364
+ * This option only has effect in headless mode (enabled in CI by default)
2162
2365
  *
2163
- * Requires `poolOptions.threads.singleThread: true` OR `poolOptions.forks.singleFork: true`.
2366
+ * @default // Same as "test.fileParallelism"
2164
2367
  */
2165
- inspect?: boolean | string;
2368
+ fileParallelism?: boolean;
2166
2369
  /**
2167
- * Debug tests by opening `node:inspector` in worker / child process and wait for debugger to connect.
2168
- * Provides similar experience as `--inspect-brk` Node CLI argument.
2370
+ * Show Vitest UI
2169
2371
  *
2170
- * Requires `poolOptions.threads.singleThread: true` OR `poolOptions.forks.singleFork: true`.
2372
+ * @default !process.env.CI
2171
2373
  */
2172
- inspectBrk?: boolean | string;
2374
+ ui?: boolean;
2173
2375
  /**
2174
- * Inspector options. If `--inspect` or `--inspect-brk` is enabled, these options will be passed to the inspector.
2376
+ * Default viewport size
2175
2377
  */
2176
- inspector?: {
2177
- /**
2178
- * Enable inspector
2179
- */
2180
- enabled?: boolean;
2181
- /**
2182
- * Port to run inspector on
2183
- */
2184
- port?: number;
2378
+ viewport?: {
2185
2379
  /**
2186
- * Host to run inspector on
2380
+ * Width of the viewport
2381
+ * @default 414
2187
2382
  */
2188
- host?: string;
2383
+ width: number;
2189
2384
  /**
2190
- * Wait for debugger to connect before running tests
2385
+ * Height of the viewport
2386
+ * @default 896
2191
2387
  */
2192
- waitForDebugger?: boolean;
2388
+ height: number;
2193
2389
  };
2194
2390
  /**
2195
- * Define variables that will be returned from `inject` in the test environment.
2196
- * @example
2197
- * ```ts
2198
- * // vitest.config.ts
2199
- * export default defineConfig({
2200
- * test: {
2201
- * provide: {
2202
- * someKey: 'someValue'
2203
- * }
2204
- * }
2205
- * })
2206
- * ```
2207
- * ```ts
2208
- * // test file
2209
- * import { inject } from 'vitest'
2210
- * const value = inject('someKey') // 'someValue'
2211
- * ```
2212
- */
2213
- provide?: Partial<ProvidedContext>;
2214
- /**
2215
- * Configuration options for expect() matches.
2391
+ * Locator options
2216
2392
  */
2217
- expect?: {
2218
- /**
2219
- * Throw an error if tests don't have any expect() assertions.
2220
- */
2221
- requireAssertions?: boolean;
2393
+ locators?: {
2222
2394
  /**
2223
- * Default options for expect.poll()
2395
+ * Attribute used to locate elements by test id
2396
+ * @default 'data-testid'
2224
2397
  */
2225
- poll?: {
2226
- /**
2227
- * Timeout in milliseconds
2228
- * @default 1000
2229
- */
2230
- timeout?: number;
2231
- /**
2232
- * Polling interval in milliseconds
2233
- * @default 50
2234
- */
2235
- interval?: number;
2236
- };
2398
+ testIdAttribute?: string;
2237
2399
  };
2238
2400
  /**
2239
- * Modify default Chai config. Vitest uses Chai for `expect` and `assert` matches.
2240
- * https://github.com/chaijs/chai/blob/4.x.x/lib/chai/config.js
2241
- */
2242
- chaiConfig?: ChaiConfig;
2243
- /**
2244
- * Stop test execution when given number of tests have failed.
2401
+ * Directory where screenshots will be saved when page.screenshot() is called
2402
+ * If not set, all screenshots are saved to __screenshots__ directory in the same folder as the test file.
2403
+ * If this is set, it will be resolved relative to the project root.
2404
+ * @default __screenshots__
2245
2405
  */
2246
- bail?: number;
2406
+ screenshotDirectory?: string;
2247
2407
  /**
2248
- * Retry the test specific number of times if it fails.
2249
- *
2250
- * @default 0
2408
+ * Should Vitest take screenshots if the test fails
2409
+ * @default !browser.ui
2251
2410
  */
2252
- retry?: number;
2411
+ screenshotFailures?: boolean;
2253
2412
  /**
2254
- * Show full diff when snapshot fails instead of a patch.
2413
+ * Scripts injected into the tester iframe.
2414
+ * @deprecated Will be removed in the future, use `testerHtmlPath` instead.
2255
2415
  */
2256
- expandSnapshotDiff?: boolean;
2416
+ testerScripts?: BrowserScript[];
2257
2417
  /**
2258
- * By default, Vitest automatically intercepts console logging during tests for extra formatting of test file, test title, etc...
2259
- * This is also required for console log preview on Vitest UI.
2260
- * However, disabling such interception might help when you want to debug a code with normal synchronus terminal console logging.
2261
- *
2262
- * This option has no effect on browser pool since Vitest preserves original logging on browser devtools.
2263
- *
2264
- * @default false
2418
+ * Path to the index.html file that will be used to run tests.
2265
2419
  */
2266
- disableConsoleIntercept?: boolean;
2420
+ testerHtmlPath?: string;
2267
2421
  /**
2268
- * Always print console stack traces.
2269
- *
2270
- * @default false
2422
+ * Scripts injected into the main window.
2271
2423
  */
2272
- printConsoleTrace?: boolean;
2424
+ orchestratorScripts?: BrowserScript[];
2273
2425
  /**
2274
- * Include "location" property inside the test definition
2275
- *
2276
- * @default false
2426
+ * Commands that will be executed on the server
2427
+ * via the browser `import("@vitest/browser/context").commands` API.
2428
+ * @see {@link https://vitest.dev/guide/browser/commands}
2277
2429
  */
2278
- includeTaskLocation?: boolean;
2430
+ commands?: Record<string, BrowserCommand<any>>;
2279
2431
  }
2280
- interface TypecheckConfig {
2281
- /**
2282
- * Run typechecking tests alongisde regular tests.
2283
- */
2284
- enabled?: boolean;
2285
- /**
2286
- * When typechecking is enabled, only run typechecking tests.
2287
- */
2288
- only?: boolean;
2289
- /**
2290
- * What tools to use for type checking.
2291
- *
2292
- * @default 'tsc'
2293
- */
2294
- checker: 'tsc' | 'vue-tsc' | (string & Record<never, never>);
2295
- /**
2296
- * Pattern for files that should be treated as test files
2297
- *
2298
- * @default ['**\/*.{test,spec}-d.?(c|m)[jt]s?(x)']
2299
- */
2300
- include: string[];
2301
- /**
2302
- * Pattern for files that should not be treated as test files
2303
- *
2304
- * @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.*']
2305
- */
2306
- exclude: string[];
2307
- /**
2308
- * Check JS files that have `@ts-check` comment.
2309
- * If you have it enabled in tsconfig, this will not overwrite it.
2310
- */
2311
- allowJs?: boolean;
2312
- /**
2313
- * Do not fail, if Vitest found errors outside the test files.
2314
- */
2315
- ignoreSourceErrors?: boolean;
2316
- /**
2317
- * Path to tsconfig, relative to the project root.
2318
- */
2319
- tsconfig?: string;
2432
+ interface BrowserCommandContext {
2433
+ testPath: string | undefined;
2434
+ provider: BrowserProvider;
2435
+ project: TestProject;
2436
+ contextId: string;
2437
+ }
2438
+ interface BrowserServerStateContext {
2439
+ files: string[];
2440
+ method: 'run' | 'collect';
2441
+ resolve: () => void;
2442
+ reject: (v: unknown) => void;
2443
+ }
2444
+ interface BrowserOrchestrator {
2445
+ createTesters: (files: string[]) => Promise<void>;
2446
+ onCancel: (reason: CancelReason) => Promise<void>;
2447
+ $close: () => void;
2448
+ }
2449
+ interface BrowserServerState {
2450
+ orchestrators: Map<string, BrowserOrchestrator>;
2451
+ getContext: (contextId: string) => BrowserServerStateContext | undefined;
2452
+ createAsyncContext: (method: 'collect' | 'run', contextId: string, files: string[]) => Promise<void>;
2320
2453
  }
2321
- interface UserConfig extends InlineConfig {
2454
+ interface BrowserServer {
2455
+ vite: ViteDevServer;
2456
+ state: BrowserServerState;
2457
+ provider: BrowserProvider;
2458
+ close: () => Promise<void>;
2459
+ initBrowserProvider: () => Promise<void>;
2460
+ parseStacktrace: (stack: string) => ParsedStack[];
2461
+ parseErrorStacktrace: (error: ErrorWithDiff, options?: StackTraceParserOptions) => ParsedStack[];
2462
+ }
2463
+ interface BrowserCommand<Payload extends unknown[]> {
2464
+ (context: BrowserCommandContext, ...payload: Payload): Awaitable$1<any>;
2465
+ }
2466
+ interface BrowserScript {
2322
2467
  /**
2323
- * Path to the config file.
2324
- *
2325
- * Default resolving to `vitest.config.*`, `vite.config.*`
2468
+ * If "content" is provided and type is "module", this will be its identifier.
2326
2469
  *
2327
- * Setting to `false` will disable config resolving.
2470
+ * If you are using TypeScript, you can add `.ts` extension here for example.
2471
+ * @default `injected-${index}.js`
2328
2472
  */
2329
- config?: string | false | undefined;
2473
+ id?: string;
2330
2474
  /**
2331
- * Do not run tests when Vitest starts.
2332
- *
2333
- * Vitest will only run tests if it's called programmatically or the test file changes.
2475
+ * JavaScript content to be injected. This string is processed by Vite plugins if type is "module".
2334
2476
  *
2335
- * CLI file filters will be ignored.
2477
+ * You can use `id` to give Vite a hint about the file extension.
2336
2478
  */
2337
- standalone?: boolean;
2479
+ content?: string;
2338
2480
  /**
2339
- * Use happy-dom
2481
+ * Path to the script. This value is resolved by Vite so it can be a node module or a file path.
2340
2482
  */
2341
- dom?: boolean;
2483
+ src?: string;
2342
2484
  /**
2343
- * Run tests that cover a list of source files
2485
+ * If the script should be loaded asynchronously.
2344
2486
  */
2345
- related?: string[] | string;
2487
+ async?: boolean;
2346
2488
  /**
2347
- * Overrides Vite mode
2348
- * @default 'test'
2489
+ * Script type.
2490
+ * @default 'module'
2349
2491
  */
2350
- mode?: string;
2492
+ type?: string;
2493
+ }
2494
+ interface ResolvedBrowserOptions extends BrowserConfigOptions {
2495
+ enabled: boolean;
2496
+ headless: boolean;
2497
+ isolate: boolean;
2498
+ fileParallelism: boolean;
2499
+ api: ApiConfig;
2500
+ ui: boolean;
2501
+ viewport: {
2502
+ width: number;
2503
+ height: number;
2504
+ };
2505
+ screenshotFailures: boolean;
2506
+ locators: {
2507
+ testIdAttribute: string;
2508
+ };
2509
+ }
2510
+
2511
+ declare class TestSpecification {
2351
2512
  /**
2352
- * Runs tests that are affected by the changes in the repository, or between specified branch or commit hash
2353
- * Requires initialized git repository
2354
- * @default false
2513
+ * @deprecated use `project` instead
2355
2514
  */
2356
- changed?: boolean | string;
2515
+ readonly 0: TestProject;
2357
2516
  /**
2358
- * Test suite shard to execute in a format of <index>/<count>.
2359
- * Will divide tests into a `count` numbers, and run only the `indexed` part.
2360
- * Cannot be used with enabled watch.
2361
- * @example --shard=2/3
2517
+ * @deprecated use `moduleId` instead
2362
2518
  */
2363
- shard?: string;
2519
+ readonly 1: string;
2364
2520
  /**
2365
- * Name of the project or projects to run.
2521
+ * @deprecated use `pool` instead
2366
2522
  */
2367
- project?: string | string[];
2523
+ readonly 2: {
2524
+ pool: Pool;
2525
+ };
2526
+ readonly project: TestProject;
2527
+ readonly moduleId: string;
2528
+ readonly pool: Pool;
2529
+ constructor(project: TestProject, moduleId: string, pool: Pool);
2530
+ toJSON(): SerializedTestSpecification;
2368
2531
  /**
2369
- * Additional exclude patterns
2532
+ * for backwards compatibility
2533
+ * @deprecated
2370
2534
  */
2371
- cliExclude?: string[];
2535
+ [Symbol.iterator](): Generator<string | TestProject, void, unknown>;
2536
+ }
2537
+
2538
+ declare class TestProject {
2539
+ /** @deprecated */
2540
+ path: string | number;
2541
+ /** @deprecated */
2542
+ options?: InitializeProjectOptions | undefined;
2372
2543
  /**
2373
- * Override vite config's clearScreen from cli
2544
+ * The global Vitest instance.
2545
+ * @experimental The public Vitest API is experimental and does not follow semver.
2374
2546
  */
2375
- clearScreen?: boolean;
2547
+ readonly vitest: Vitest;
2376
2548
  /**
2377
- * benchmark.compare option exposed at the top level for cli
2549
+ * Resolved global configuration. If there are no workspace projects, this will be the same as `config`.
2378
2550
  */
2379
- compare?: string;
2551
+ readonly globalConfig: ResolvedConfig;
2380
2552
  /**
2381
- * benchmark.outputJson option exposed at the top level for cli
2553
+ * Browser instance if the browser is enabled. This is initialized when the tests run for the first time.
2382
2554
  */
2383
- outputJson?: string;
2555
+ browser?: BrowserServer;
2556
+ /** @deprecated use `vitest` instead */
2557
+ ctx: Vitest;
2384
2558
  /**
2385
- * Directory of blob reports to merge
2386
- * @default '.vitest-reports'
2559
+ * Temporary directory for the project. This is unique for each project. Vitest stores transformed content here.
2387
2560
  */
2388
- mergeReports?: string;
2389
- }
2390
- interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'browser' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'benchmark' | 'shard' | 'cache' | 'sequence' | 'typecheck' | 'runner' | 'poolOptions' | 'pool' | 'cliExclude' | 'diff' | 'setupFiles' | 'snapshotEnvironment' | 'bail'> {
2391
- mode: VitestRunMode;
2392
- base?: string;
2393
- diff?: string;
2394
- bail?: number;
2395
- setupFiles: string[];
2396
- snapshotEnvironment?: string;
2397
- config?: string;
2398
- filters?: string[];
2399
- testNamePattern?: RegExp;
2400
- related?: string[];
2401
- coverage: ResolvedCoverageOptions;
2402
- snapshotOptions: SnapshotStateOptions;
2403
- browser: ResolvedBrowserOptions;
2404
- pool: Pool;
2405
- poolOptions?: ResolvedPoolOptions;
2406
- reporters: (InlineReporter | ReporterWithOptions)[];
2407
- defines: Record<string, any>;
2408
- api?: ApiConfig;
2409
- cliExclude?: string[];
2410
- benchmark?: Required<Omit<BenchmarkUserOptions, 'outputFile' | 'compare' | 'outputJson'>> & Pick<BenchmarkUserOptions, 'outputFile' | 'compare' | 'outputJson'>;
2411
- shard?: {
2412
- index: number;
2413
- count: number;
2414
- };
2415
- cache: {
2416
- /**
2417
- * @deprecated
2418
- */
2419
- dir: string;
2420
- } | false;
2421
- sequence: {
2422
- sequencer: TestSequencerConstructor;
2423
- hooks: SequenceHooks;
2424
- setupFiles: SequenceSetupFiles;
2425
- shuffle?: boolean;
2426
- concurrent?: boolean;
2427
- seed: number;
2428
- };
2429
- typecheck: Omit<TypecheckConfig, 'enabled'> & {
2430
- enabled: boolean;
2431
- };
2432
- runner?: string;
2433
- maxWorkers: number;
2434
- minWorkers: number;
2435
- }
2436
- 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';
2437
- type ProjectConfig = Omit<UserConfig, NonProjectOptions | 'sequencer' | 'deps' | 'poolOptions'> & {
2438
- sequencer?: Omit<SequenceOptions, 'sequencer' | 'seed'>;
2439
- deps?: Omit<DepsOptions, 'moduleDirectories'>;
2440
- poolOptions?: {
2441
- threads?: Pick<NonNullable<PoolOptions['threads']>, 'singleThread' | 'isolate'>;
2442
- vmThreads?: Pick<NonNullable<PoolOptions['vmThreads']>, 'singleThread'>;
2443
- forks?: Pick<NonNullable<PoolOptions['forks']>, 'singleFork' | 'isolate'>;
2444
- };
2445
- };
2446
- type ResolvedProjectConfig = Omit<ResolvedConfig, NonProjectOptions>;
2447
- interface UserWorkspaceConfig extends UserConfig$1 {
2448
- test?: ProjectConfig;
2449
- }
2450
- type UserProjectConfigFn = (env: ConfigEnv) => UserWorkspaceConfig | Promise<UserWorkspaceConfig>;
2451
- type UserProjectConfigExport = UserWorkspaceConfig | Promise<UserWorkspaceConfig> | UserProjectConfigFn;
2452
- type WorkspaceProjectConfiguration = string | (UserProjectConfigExport & {
2561
+ readonly tmpDir: string;
2562
+ vitenode: ViteNodeServer;
2563
+ runner: ViteNodeRunner;
2564
+ typechecker?: Typechecker;
2565
+ private closingPromise;
2566
+ private testFilesList;
2567
+ private typecheckFilesList;
2568
+ private _globalSetups?;
2569
+ private _provided;
2570
+ private _config?;
2571
+ private _vite?;
2572
+ constructor(
2573
+ /** @deprecated */
2574
+ path: string | number, vitest: Vitest,
2575
+ /** @deprecated */
2576
+ options?: InitializeProjectOptions | undefined);
2453
2577
  /**
2454
- * Relative path to the extendable config. All other options will be merged with this config.
2455
- * @example '../vite.config.ts'
2578
+ * Provide a value to the test context. This value will be available to all tests with `inject`.
2456
2579
  */
2457
- extends?: string;
2458
- });
2459
-
2460
- declare class TestProject {
2580
+ provide<T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]): void;
2461
2581
  /**
2462
- * The global vitest instance.
2463
- * @experimental The public Vitest API is experimental and does not follow semver.
2582
+ * Get the provided context. The project context is merged with the global context.
2464
2583
  */
2465
- readonly vitest: Vitest;
2584
+ getProvidedContext(): ProvidedContext;
2466
2585
  /**
2467
- * The workspace project this test project is associated with.
2468
- * @experimental The public Vitest API is experimental and does not follow semver.
2586
+ * Creates a new test specification. Specifications describe how to run tests.
2587
+ * @param moduleId The file path
2469
2588
  */
2470
- readonly workspaceProject: WorkspaceProject;
2589
+ createSpecification(moduleId: string, pool?: string): TestSpecification;
2590
+ toJSON(): SerializedTestProject;
2471
2591
  /**
2472
2592
  * Vite's dev server instance. Every workspace project has its own server.
2473
2593
  */
2474
- readonly vite: ViteDevServer;
2594
+ get vite(): ViteDevServer;
2475
2595
  /**
2476
2596
  * Resolved project configuration.
2477
2597
  */
2478
- readonly config: ResolvedProjectConfig;
2479
- /**
2480
- * Resolved global configuration. If there are no workspace projects, this will be the same as `config`.
2481
- */
2482
- readonly globalConfig: ResolvedConfig;
2598
+ get config(): ResolvedConfig;
2483
2599
  /**
2484
2600
  * The name of the project or an empty string if not set.
2485
2601
  */
2486
- readonly name: string;
2487
- constructor(workspaceProject: WorkspaceProject);
2602
+ get name(): string;
2488
2603
  /**
2489
2604
  * Serialized project configuration. This is the config that tests receive.
2490
2605
  */
2491
2606
  get serializedConfig(): SerializedConfig;
2607
+ /** @deprecated use `vite` instead */
2608
+ get server(): ViteDevServer;
2492
2609
  /**
2493
- * Custom context provided to the project.
2610
+ * Check if this is the root project. The root project is the one that has the root config.
2494
2611
  */
2495
- context(): ProvidedContext;
2612
+ isRootProject(): boolean;
2613
+ /** @deprecated use `isRootProject` instead */
2614
+ isCore(): boolean;
2615
+ /** @deprecated use `createSpecification` instead */
2616
+ createSpec(moduleId: string, pool: string): WorkspaceSpec;
2617
+ /** @deprecated */
2618
+ initializeGlobalSetup(): Promise<void>;
2619
+ /** @deprecated */
2620
+ teardownGlobalSetup(): Promise<void>;
2621
+ /** @deprecated use `vitest.logger` instead */
2622
+ get logger(): Logger;
2623
+ /** @deprecated use `.vite` or `.browser.vite` directly */
2624
+ getModulesByFilepath(file: string): Set<ModuleNode>;
2625
+ /** @deprecated use `.vite` or `.browser.vite` directly */
2626
+ getModuleById(id: string): ModuleNode | undefined;
2627
+ /** @deprecated use `.vite` or `.browser.vite` directly */
2628
+ getSourceMapModuleById(id: string): TransformResult$1['map'] | undefined;
2629
+ /** @deprecated use `vitest.reporters` instead */
2630
+ get reporters(): Reporter[];
2496
2631
  /**
2497
- * Provide a custom serializable context to the project. This context will be available for tests once they run.
2632
+ * Get all files in the project that match the globs in the config and the filters.
2633
+ * @param filters String filters to match the test files.
2498
2634
  */
2499
- provide<T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]): void;
2500
- toJSON(): SerializedTestProject;
2635
+ globTestFiles(filters?: string[]): Promise<{
2636
+ /**
2637
+ * Test files that match the filters.
2638
+ */
2639
+ testFiles: string[];
2640
+ /**
2641
+ * Typecheck test files that match the filters. This will be empty unless `typecheck.enabled` is `true`.
2642
+ */
2643
+ typecheckTestFiles: string[];
2644
+ }>;
2645
+ private globAllTestFiles;
2646
+ isBrowserEnabled(): boolean;
2647
+ /** @deprecated use `serializedConfig` instead */
2648
+ getSerializableConfig(): SerializedConfig;
2649
+ /**
2650
+ * Test if a file matches the test globs. This does the actual glob matching unlike `isTestFile`.
2651
+ */
2652
+ matchesTestGlob(filepath: string, source?: string): boolean;
2653
+ /** @deprecated use `matchesTestGlob` instead */
2654
+ isTargetFile(id: string, source?: string): Promise<boolean>;
2655
+ private isInSourceTestCode;
2656
+ private filterFiles;
2657
+ /**
2658
+ * Closes the project and all associated resources. This can only be called once; the closing promise is cached until the server restarts.
2659
+ * If the resources are needed again, create a new project.
2660
+ */
2661
+ close(): Promise<void>;
2662
+ /** @deprecated use `name` instead */
2663
+ getName(): string;
2664
+ /** @deprecated internal */
2665
+ setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
2666
+ private _serializeOverridenConfig;
2667
+ private clearTmpDir;
2668
+ /** @deprecated */
2669
+ initBrowserProvider(): Promise<void>;
2501
2670
  }
2671
+
2502
2672
  interface SerializedTestProject {
2503
2673
  name: string;
2504
2674
  serializedConfig: SerializedConfig;
2505
2675
  context: ProvidedContext;
2506
2676
  }
2507
-
2508
- declare class TestSpecification {
2509
- /**
2510
- * @deprecated use `project` instead
2511
- */
2512
- readonly 0: WorkspaceProject;
2513
- /**
2514
- * @deprecated use `moduleId` instead
2515
- */
2516
- readonly 1: string;
2517
- /**
2518
- * @deprecated use `pool` instead
2519
- */
2520
- readonly 2: {
2521
- pool: Pool;
2522
- };
2523
- readonly project: TestProject;
2524
- readonly moduleId: string;
2525
- readonly pool: Pool;
2526
- constructor(workspaceProject: WorkspaceProject, moduleId: string, pool: Pool);
2527
- toJSON(): SerializedTestSpecification;
2528
- /**
2529
- * for backwards compatibility
2530
- * @deprecated
2531
- */
2532
- [Symbol.iterator](): Generator<string | WorkspaceProject, void, unknown>;
2677
+ interface InitializeProjectOptions extends UserWorkspaceConfig {
2678
+ workspaceConfigPath: string;
2679
+ extends?: string;
2533
2680
  }
2534
2681
 
2535
2682
  /**
@@ -2539,7 +2686,7 @@ type WorkspaceSpec = TestSpecification & [
2539
2686
  /**
2540
2687
  * @deprecated use spec.project instead
2541
2688
  */
2542
- project: WorkspaceProject,
2689
+ project: TestProject,
2543
2690
  /**
2544
2691
  * @deprecated use spec.moduleId instead
2545
2692
  */
@@ -2558,7 +2705,7 @@ interface ProcessPool {
2558
2705
  collectTests: RunWithFiles;
2559
2706
  close?: () => Awaitable$1<void>;
2560
2707
  }
2561
- declare function getFilePoolName(project: WorkspaceProject, file: string): Pool;
2708
+ declare function getFilePoolName(project: TestProject, file: string): Pool;
2562
2709
 
2563
2710
  interface SuiteResultCache {
2564
2711
  failed: boolean;
@@ -2625,17 +2772,18 @@ declare class StateManager {
2625
2772
  * Return files that were running or collected.
2626
2773
  */
2627
2774
  getFiles(keys?: string[]): File[];
2775
+ getTestModules(keys?: string[]): TestModule[];
2628
2776
  getFilepaths(): string[];
2629
2777
  getFailedFilepaths(): string[];
2630
2778
  collectPaths(paths?: string[]): void;
2631
- collectFiles(project: WorkspaceProject, files?: File[]): void;
2632
- clearFiles(project: WorkspaceProject, paths?: string[]): void;
2633
- updateId(task: Task, project: WorkspaceProject): void;
2779
+ collectFiles(project: TestProject, files?: File[]): void;
2780
+ clearFiles(project: TestProject, paths?: string[]): void;
2781
+ updateId(task: Task, project: TestProject): void;
2634
2782
  getReportedEntity(task: Task): TestCase | TestSuite | TestModule | undefined;
2635
2783
  updateTasks(packs: TaskResultPack[]): void;
2636
2784
  updateUserLog(log: UserConsoleLog): void;
2637
2785
  getCountOfFailedTests(): number;
2638
- cancelFiles(files: string[], project: WorkspaceProject): void;
2786
+ cancelFiles(files: string[], project: TestProject): void;
2639
2787
  }
2640
2788
 
2641
2789
  interface VitestOptions {
@@ -2669,15 +2817,14 @@ declare class Vitest {
2669
2817
  restartsCount: number;
2670
2818
  runner: ViteNodeRunner;
2671
2819
  packageInstaller: VitestPackageInstaller;
2672
- private coreWorkspaceProject;
2673
2820
  /** @private */
2674
- resolvedProjects: WorkspaceProject[];
2675
- projects: WorkspaceProject[];
2821
+ resolvedProjects: TestProject[];
2822
+ projects: TestProject[];
2676
2823
  distPath: string;
2677
2824
  private _cachedSpecs;
2678
2825
  private _workspaceConfigPath?;
2679
2826
  /** @deprecated use `_cachedSpecs` */
2680
- projectTestFiles: Map<string, WorkspaceSpec[]>;
2827
+ projectTestFiles: Map<string, TestSpecification[]>;
2681
2828
  /** @private */
2682
2829
  _browserLastPort: number;
2683
2830
  constructor(mode: VitestRunMode, options?: VitestOptions);
@@ -2685,22 +2832,15 @@ declare class Vitest {
2685
2832
  private _onClose;
2686
2833
  private _onSetServer;
2687
2834
  private _onCancelListeners;
2835
+ private _onUserTestsRerun;
2688
2836
  setServer(options: UserConfig, server: ViteDevServer, cliOptions: UserConfig): Promise<void>;
2689
2837
  provide<T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]): void;
2690
- /**
2691
- * @deprecated internal, use `_createCoreProject` instead
2692
- */
2693
- createCoreProject(): Promise<WorkspaceProject>;
2694
- /**
2695
- * @internal
2696
- */
2697
- _createCoreProject(): Promise<WorkspaceProject>;
2698
- getCoreWorkspaceProject(): WorkspaceProject;
2838
+ getRootTestProject(): TestProject;
2699
2839
  /**
2700
2840
  * @deprecated use Reported Task API instead
2701
2841
  */
2702
- getProjectByTaskId(taskId: string): WorkspaceProject;
2703
- getProjectByName(name?: string): WorkspaceProject;
2842
+ getProjectByTaskId(taskId: string): TestProject;
2843
+ getProjectByName(name?: string): TestProject;
2704
2844
  private getWorkspaceConfigPath;
2705
2845
  private resolveWorkspace;
2706
2846
  private initCoverageProvider;
@@ -2718,13 +2858,15 @@ declare class Vitest {
2718
2858
  * @deprecated remove when vscode extension supports "getFileWorkspaceSpecs"
2719
2859
  */
2720
2860
  getProjectsByTestFile(file: string): WorkspaceSpec[];
2721
- getFileWorkspaceSpecs(file: string): WorkspaceSpec[];
2861
+ getFileWorkspaceSpecs(file: string): TestSpecification[];
2722
2862
  initializeGlobalSetup(paths: TestSpecification[]): Promise<void>;
2723
2863
  runFiles(specs: TestSpecification[], allTestsRun: boolean): Promise<void>;
2724
2864
  collectFiles(specs: WorkspaceSpec[]): Promise<void>;
2725
2865
  cancelCurrentRun(reason: CancelReason): Promise<void>;
2726
2866
  initBrowserServers(): Promise<void>;
2727
- rerunFiles(files?: string[], trigger?: string, allTestsRun?: boolean): Promise<void>;
2867
+ rerunFiles(files?: string[], trigger?: string, allTestsRun?: boolean, resetTestNamePattern?: boolean): Promise<void>;
2868
+ private isSuite;
2869
+ rerunTask(id: string): Promise<void>;
2728
2870
  changeProjectName(pattern: string): Promise<void>;
2729
2871
  changeNamePattern(pattern: string, files?: string[], trigger?: string): Promise<void>;
2730
2872
  changeFilenamePattern(pattern: string, files?: string[]): Promise<void>;
@@ -2732,7 +2874,7 @@ declare class Vitest {
2732
2874
  updateSnapshot(files?: string[]): Promise<void>;
2733
2875
  private _rerunTimer;
2734
2876
  private scheduleRerun;
2735
- getModuleProjects(filepath: string): WorkspaceProject[];
2877
+ getModuleProjects(filepath: string): TestProject[];
2736
2878
  /**
2737
2879
  * Watch only the specified tests. If no tests are provided, all tests will be watched.
2738
2880
  */
@@ -2758,7 +2900,7 @@ declare class Vitest {
2758
2900
  getTestFilepaths(): Promise<string[]>;
2759
2901
  globTestSpecs(filters?: string[]): Promise<WorkspaceSpec[]>;
2760
2902
  /**
2761
- * @deprecated use globTestSpecs instead
2903
+ * @deprecated use `globTestSpecs` instead
2762
2904
  */
2763
2905
  globTestFiles(filters?: string[]): Promise<WorkspaceSpec[]>;
2764
2906
  private ensureSpecCached;
@@ -2767,6 +2909,7 @@ declare class Vitest {
2767
2909
  onAfterSetServer(fn: OnServerRestartHandler): void;
2768
2910
  onCancel(fn: (reason: CancelReason) => void): void;
2769
2911
  onClose(fn: () => void): void;
2912
+ onTestsRerun(fn: OnTestsRerunHandler): void;
2770
2913
  }
2771
2914
 
2772
- export { type HTMLOptions as $, type ApiConfig as A, type BaseCoverageOptions as B, type CoverageProvider as C, type DepsOptimizationOptions as D, type ResolvedConfig as E, type ProjectConfig as F, type BenchmarkUserOptions as G, type VitestOptions as H, type InlineConfig as I, WorkspaceProject as J, type TestSequencer as K, Logger as L, type WorkspaceSpec as M, TestModule as N, type ModuleDiagnostic as O, type Pool as P, VitestPackageInstaller as Q, type ResolvedCoverageOptions as R, type SerializedTestSpecification as S, type TscErrorInfo as T, type UserWorkspaceConfig as U, Vitest as V, type WorkspaceProjectConfiguration as W, type ProcessPool as X, getFilePoolName as Y, TestProject as Z, type SerializedTestProject as _, type ReportContext as a, type JsonOptions$1 as a0, type JUnitOptions as a1, TestCase as a2, TestSuite as a3, type TaskOptions as a4, TestCollection as a5, type TestDiagnostic as a6, type TestResult as a7, type TestResultFailed as a8, type TestResultPassed as a9, VerboseReporter as aA, BaseReporter as aB, TestFile as aC, type FileDiagnostic as aD, ReportersMap as aE, type BuiltinReporters as aF, type BuiltinReporterOptions as aG, type JsonAssertionResult as aH, type JsonTestResult as aI, type JsonTestResults as aJ, BenchmarkReportsMap as aK, type BenchmarkBuiltinReporters as aL, type TestResultSkipped as aa, type TestSequencerConstructor as ab, TestSpecification as ac, type BrowserBuiltinProvider as ad, type BrowserCommand as ae, type BrowserCommandContext as af, type BrowserOrchestrator as ag, type BrowserProvider as ah, type BrowserProviderInitializationOptions as ai, type BrowserProviderModule as aj, type BrowserProviderOptions as ak, type BrowserServer as al, type BrowserServerState as am, type BrowserServerStateContext as an, type CDPSession as ao, type ResolvedBrowserOptions as ap, type ResolvedProjectConfig as aq, BasicReporter as ar, DefaultReporter as as, DotReporter as at, GithubActionsReporter as au, HangingProcessReporter as av, JsonReporter as aw, JUnitReporter as ax, TapFlatReporter as ay, TapReporter as az, type CoverageProviderModule as b, type CoverageV8Options as c, type UserProjectConfigFn as d, type UserProjectConfigExport as e, type VitestEnvironment as f, type RawErrsMap as g, type CollectLineNumbers as h, type CollectLines as i, type RootAndTarget as j, type Context as k, type CoverageReporter as l, type CoverageProviderName as m, type CoverageOptions as n, type CoverageIstanbulOptions as o, type CustomProviderOptions as p, type Reporter as q, type BrowserScript as r, type BrowserConfigOptions as s, type BuiltinEnvironment as t, type PoolOptions as u, type CSSModuleScopeStrategy as v, type VitestRunMode as w, type TransformModePatterns as x, type TypecheckConfig as y, type UserConfig as z };
2915
+ export { type SerializedTestProject as $, type ApiConfig as A, type BaseCoverageOptions as B, CoverageMap as C, type DepsOptimizationOptions as D, type TypecheckConfig as E, type UserConfig as F, type ResolvedConfig as G, type ProjectConfig as H, type InlineConfig as I, type BenchmarkUserOptions as J, type VitestOptions as K, Logger as L, TestProject as M, type TestSequencer as N, type WorkspaceSpec as O, type Pool as P, TestModule 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, type ModuleDiagnostic as X, VitestPackageInstaller as Y, type ProcessPool as Z, getFilePoolName as _, type ReportContext as a, type HTMLOptions as a0, type JsonOptions$1 as a1, type JUnitOptions as a2, TestCase as a3, TestSuite as a4, type TaskOptions as a5, TestCollection as a6, type TestDiagnostic as a7, type TestResult as a8, type TestResultFailed as a9, JUnitReporter as aA, TapFlatReporter as aB, TapReporter as aC, VerboseReporter as aD, BaseReporter as aE, TestFile as aF, type FileDiagnostic as aG, ReportersMap as aH, type BuiltinReporters as aI, type BuiltinReporterOptions as aJ, type JsonAssertionResult as aK, type JsonTestResult as aL, type JsonTestResults as aM, BenchmarkReportsMap as aN, type BenchmarkBuiltinReporters as aO, type TestResultPassed as aa, type TestResultSkipped as ab, type TestSequencerConstructor as ac, TestSpecification as ad, type BrowserBuiltinProvider as ae, type BrowserCommand as af, type BrowserCommandContext as ag, type BrowserOrchestrator as ah, type BrowserProvider as ai, type BrowserProviderInitializationOptions as aj, type BrowserProviderModule as ak, type BrowserProviderOptions as al, type BrowserServer as am, type BrowserServerState as an, type BrowserServerStateContext as ao, type CDPSession as ap, type ResolvedBrowserOptions as aq, type ResolvedProjectConfig as ar, type ResolveSnapshotPathHandler as as, type ResolveSnapshotPathHandlerContext as at, BasicReporter as au, DefaultReporter as av, DotReporter as aw, GithubActionsReporter as ax, HangingProcessReporter as ay, JsonReporter as az, type CoverageProvider as b, type CoverageProviderModule as c, type CoverageV8Options as d, type UserProjectConfigFn as e, type UserProjectConfigExport as f, type VitestEnvironment as g, type RawErrsMap as h, type TscErrorInfo as i, type CollectLineNumbers as j, type CollectLines as k, type RootAndTarget as l, type Context as m, type CoverageReporter as n, type CoverageProviderName as o, type CoverageOptions as p, type CoverageIstanbulOptions as q, type CustomProviderOptions as r, type Reporter as s, type BrowserScript as t, type BrowserConfigOptions as u, type BuiltinEnvironment as v, type PoolOptions as w, type CSSModuleScopeStrategy as x, type VitestRunMode as y, type TransformModePatterns as z };