vitest 5.0.0-beta.4 → 5.0.0-beta.6

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 (58) hide show
  1. package/LICENSE.md +0 -17
  2. package/dist/browser.d.ts +8 -6
  3. package/dist/browser.js +5 -3
  4. package/dist/chunks/artifact.BNnEI1sJ.js +2770 -0
  5. package/dist/chunks/{base.BEGVMQrS.js → base.BKfXyFN7.js} +12 -12
  6. package/dist/chunks/browser.d.DoM6vBOs.d.ts +64 -0
  7. package/dist/chunks/{cac.CyXAEMkE.js → cac.DKrA6qEB.js} +15 -7
  8. package/dist/chunks/{cli-api.DJMXq34b.js → cli-api.cZcvaUFI.js} +491 -852
  9. package/dist/chunks/config.d.CKWK3nld.d.ts +2920 -0
  10. package/dist/chunks/{console.B3IRP8fX.js → console.DjVIMaXT.js} +4 -4
  11. package/dist/chunks/{coverage.d.g2xbl2sP.d.ts → coverage.d.CCNrKR65.d.ts} +2 -0
  12. package/dist/chunks/{creator.D66cVXYh.js → creator.C4nK7Krt.js} +19 -4
  13. package/dist/chunks/{defaults.CUUnbOrq.js → defaults.B_pFOTYy.js} +1 -1
  14. package/dist/chunks/{globals.BuY-yD0m.js → globals.CzUA1xn8.js} +12 -12
  15. package/dist/chunks/{index.CcluKS59.js → index.B4UTDegh.js} +6 -6
  16. package/dist/chunks/{nativeModuleRunner.BOeMnHl4.js → index.CesbTg1C.js} +3 -34
  17. package/dist/chunks/{index.CE58PZNH.js → index.D6NDM5O1.js} +515 -121
  18. package/dist/chunks/{index.nQFVd50u.js → index.DNRmy2jU.js} +32 -10
  19. package/dist/chunks/{index.og1WyBLx.js → index.Djaij2xr.js} +660 -58
  20. package/dist/chunks/{init-forks.Ce3vGWgL.js → init-forks.BG4bCDny.js} +1 -1
  21. package/dist/chunks/{init-threads.8e1OLv5v.js → init-threads.DLtIP5Qq.js} +1 -1
  22. package/dist/chunks/{init.6qx-LaHs.js → init.DTAQFCjl.js} +10 -6
  23. package/dist/chunks/{nativeModuleMocker.DDZfQXLs.js → nativeModuleMocker.BKtCThoO.js} +2 -3
  24. package/dist/chunks/nativeModuleRunner.WlMdOB52.js +36 -0
  25. package/dist/chunks/{node.CwFbQqI1.js → node.C9I1sbE9.js} +1 -2
  26. package/dist/chunks/{plugin.d.B7MTG_Fe.d.ts → plugin.d.Bpge8Jye.d.ts} +94 -37
  27. package/dist/chunks/{rpc.DFRWVnRh.js → rpc.DZEh5xnQ.js} +1 -1
  28. package/dist/chunks/{rpc.d.OQ_EZi1Z.d.ts → rpc.d.C6-dGZ2f.d.ts} +1 -2
  29. package/dist/chunks/{setup-common.DdEF_hkE.js → setup-common.ZNdeu5wa.js} +2 -2
  30. package/dist/chunks/{global.d.BtKPuz2X.d.ts → task-utils.d.mMDXJF_I.d.ts} +30 -89
  31. package/dist/chunks/{utils.BX5Fg8C4.js → utils.DYj33du9.js} +1 -17
  32. package/dist/chunks/{vm.Bu7mmcZq.js → vm.CeHWcIrU.js} +4 -4
  33. package/dist/chunks/{worker.d.yR22cs6X.d.ts → worker.d.JES7ffPK.d.ts} +3 -3
  34. package/dist/cli.js +1 -1
  35. package/dist/config.cjs +1 -1
  36. package/dist/config.d.ts +12 -13
  37. package/dist/config.js +1 -1
  38. package/dist/index.d.ts +416 -21
  39. package/dist/index.js +9 -9
  40. package/dist/module-evaluator.d.ts +7 -4
  41. package/dist/module-evaluator.js +7 -0
  42. package/dist/node.d.ts +31 -18
  43. package/dist/node.js +22 -16
  44. package/dist/runtime.d.ts +9 -3
  45. package/dist/runtime.js +4 -5
  46. package/dist/task-utils.js +296 -0
  47. package/dist/worker.d.ts +7 -6
  48. package/dist/worker.js +15 -14
  49. package/dist/workers/forks.js +16 -15
  50. package/dist/workers/runVmTests.js +10 -10
  51. package/dist/workers/threads.js +16 -15
  52. package/dist/workers/vmForks.js +8 -8
  53. package/dist/workers/vmThreads.js +8 -8
  54. package/package.json +18 -19
  55. package/dist/chunks/browser.d.BGxB4Xum.d.ts +0 -878
  56. package/dist/chunks/config.d.DXq1aBpy.d.ts +0 -244
  57. package/dist/chunks/environment.d-DOJxxZV9.d.DOJxxZV9.d.ts +0 -17
  58. package/dist/chunks/general.d.DFAHgpC2.d.ts +0 -247
@@ -0,0 +1,2920 @@
1
+ import { OptionsReceived, Plugin, PrettyFormatOptions } from '@vitest/pretty-format';
2
+ import { ParsedStack, TestError, Awaitable } from '@vitest/utils';
3
+ import { diff, printDiffOrStringify, SerializedDiffOptions } from '@vitest/utils/diff';
4
+ import { MockInstance } from '@vitest/spy';
5
+ import { Formatter } from 'tinyrainbow';
6
+ import { stringify } from '@vitest/utils/display';
7
+ import { Fn, FnOptions, BenchOptions, TaskResultCompleted, TaskResultRuntimeInfo, TaskResultTimestampProviderInfo, Statistics } from 'tinybench';
8
+
9
+ type VoidVarArgsFunc = (...args: unknown[]) => void;
10
+ type SetImmediate = (callback: VoidVarArgsFunc, ...args: unknown[]) => NodeImmediate;
11
+ type SetTimeout = (callback: VoidVarArgsFunc, delay?: number, ...args: unknown[]) => TimerId;
12
+ type ClearTimeout = (id?: TimerId) => void;
13
+ type SetInterval = (callback: VoidVarArgsFunc, delay?: number, ...args: unknown[]) => TimerId;
14
+ type ClearInterval = (id?: TimerId) => void;
15
+ type QueueMicrotask = (callback: VoidVarArgsFunc) => void;
16
+ type TimeRemaining = () => number;
17
+ type IdleDeadline = {
18
+ didTimeout: boolean;
19
+ timeRemaining: TimeRemaining;
20
+ };
21
+ type RequestIdleCallbackCallback = (deadline: IdleDeadline) => any;
22
+ type RequestIdleCallback = (callback: RequestIdleCallbackCallback, options?: {
23
+ timeout?: number;
24
+ }) => number;
25
+ type AnimationFrameCallback = (timestamp: number) => any;
26
+ type RequestAnimationFrame = (callback: AnimationFrameCallback) => TimerId;
27
+ type CancelAnimationFrame = (id: TimerId) => void;
28
+ type CancelIdleCallback = (id: TimerId) => void;
29
+ type ClearImmediate = (id: NodeImmediate) => void;
30
+ type TemporalTimelike = {
31
+ epochMilliseconds: number;
32
+ };
33
+ type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime" | "requestAnimationFrame" | "cancelAnimationFrame" | "requestIdleCallback" | "cancelIdleCallback" | "performance" | "queueMicrotask" | "Intl" | "Temporal";
34
+ type TimerId = number | NodeImmediate | Timer;
35
+ type GlobalObject = Record<string, any> & {
36
+ setTimeout?: SetTimeout;
37
+ clearTimeout?: ClearTimeout;
38
+ setInterval?: SetInterval;
39
+ clearInterval?: ClearInterval;
40
+ setImmediate?: SetImmediate;
41
+ clearImmediate?: ClearImmediate;
42
+ queueMicrotask?: QueueMicrotask;
43
+ requestAnimationFrame?: RequestAnimationFrame;
44
+ cancelAnimationFrame?: CancelAnimationFrame;
45
+ requestIdleCallback?: RequestIdleCallback;
46
+ cancelIdleCallback?: CancelIdleCallback;
47
+ process?: any;
48
+ performance?: any;
49
+ Performance?: any;
50
+ Intl?: any;
51
+ Temporal?: any;
52
+ Promise?: typeof Promise;
53
+ Date: typeof Date & {
54
+ isFake?: boolean;
55
+ toSource?: () => string;
56
+ clock?: any;
57
+ };
58
+ };
59
+ type TimerInitialProps = {
60
+ func: VoidVarArgsFunc;
61
+ args?: unknown[];
62
+ type?: 'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback';
63
+ delay?: number;
64
+ callAt?: number;
65
+ createdAt?: number;
66
+ immediate?: boolean;
67
+ id?: number;
68
+ error?: Error;
69
+ interval?: number;
70
+ animation?: boolean;
71
+ requestIdleCallback?: boolean;
72
+ order?: number;
73
+ heapIndex?: number;
74
+ };
75
+ type Config = {
76
+ now?: number | Date | TemporalTimelike;
77
+ toFake?: FakeMethod[];
78
+ toNotFake?: FakeMethod[];
79
+ loopLimit?: number;
80
+ shouldAdvanceTime?: boolean;
81
+ advanceTimeDelta?: number;
82
+ shouldClearNativeTimers?: boolean;
83
+ ignoreMissingTimers?: boolean;
84
+ target?: GlobalObject;
85
+ };
86
+ type Timer = TimerInitialProps;
87
+ type NodeImmediateHasRef = () => boolean;
88
+ type NodeImmediateRef = () => NodeImmediate;
89
+ type NodeImmediateUnref = () => NodeImmediate;
90
+ type NodeImmediate = {
91
+ hasRef: NodeImmediateHasRef;
92
+ ref: NodeImmediateRef;
93
+ unref: NodeImmediateUnref;
94
+ };
95
+
96
+ interface SnapshotEnvironment {
97
+ getVersion: () => string;
98
+ getHeader: () => string;
99
+ resolvePath: (filepath: string) => Promise<string>;
100
+ resolveRawPath: (testPath: string, rawPath: string) => Promise<string>;
101
+ saveSnapshotFile: (filepath: string, snapshot: string) => Promise<void>;
102
+ readSnapshotFile: (filepath: string) => Promise<string | null>;
103
+ removeSnapshotFile: (filepath: string) => Promise<void>;
104
+ processStackTrace?: (stack: ParsedStack) => ParsedStack;
105
+ }
106
+ interface SnapshotEnvironmentOptions {
107
+ snapshotsDirName?: string;
108
+ }
109
+
110
+ interface DomainMatchResult {
111
+ pass: boolean;
112
+ message?: string;
113
+ /**
114
+ * The captured value viewed through the template's lens.
115
+ *
116
+ * Where the template uses patterns (e.g. regexes) or omits details,
117
+ * the resolved string adopts those patterns. Where the template doesn't
118
+ * match, the resolved string uses literal captured values instead.
119
+ *
120
+ * Used for two purposes:
121
+ * - **Diff display** (actual side): compared against `expected`
122
+ * so the diff highlights only genuine mismatches, not pattern-vs-literal noise.
123
+ * - **Snapshot update** (`--update`): written as the new snapshot content,
124
+ * preserving user-edited patterns from matched regions while incorporating
125
+ * actual values for mismatched regions.
126
+ *
127
+ * When omitted, falls back to `render(capture(received))` (the raw rendered value).
128
+ */
129
+ resolved?: string;
130
+ /**
131
+ * The stored template re-rendered as a string, representing what the user
132
+ * originally wrote or last saved.
133
+ *
134
+ * Used as the expected side in diff display.
135
+ *
136
+ * When omitted, falls back to the raw snapshot string from the snap file
137
+ * or inline snapshot.
138
+ */
139
+ expected?: string;
140
+ }
141
+ interface DomainSnapshotAdapter<
142
+ Captured = unknown,
143
+ Expected = unknown
144
+ > {
145
+ name: string;
146
+ capture: (received: unknown) => Captured;
147
+ render: (captured: Captured) => string;
148
+ parseExpected: (input: string) => Expected;
149
+ match: (captured: Captured, expected: Expected) => DomainMatchResult;
150
+ }
151
+
152
+ /**
153
+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
154
+ *
155
+ * This source code is licensed under the MIT license found in the
156
+ * LICENSE file in the root directory of this source tree.
157
+ */
158
+
159
+ declare class DefaultMap<
160
+ K,
161
+ V
162
+ > extends Map<K, V> {
163
+ private defaultFn;
164
+ constructor(defaultFn: (key: K) => V, entries?: Iterable<readonly [K, V]>);
165
+ get(key: K): V;
166
+ }
167
+ declare class CounterMap<K> extends DefaultMap<K, number> {
168
+ constructor();
169
+ _total: number | undefined;
170
+ valueOf(): number;
171
+ increment(key: K): void;
172
+ total(): number;
173
+ }
174
+
175
+ interface SnapshotReturnOptions {
176
+ actual: string;
177
+ count: number;
178
+ expected?: string;
179
+ key: string;
180
+ pass: boolean;
181
+ }
182
+ interface SaveStatus {
183
+ deleted: boolean;
184
+ saved: boolean;
185
+ }
186
+ interface ExpectedSnapshot {
187
+ key: string;
188
+ count: number;
189
+ data?: string;
190
+ markAsChecked: () => void;
191
+ }
192
+ declare class SnapshotState {
193
+ testFilePath: string;
194
+ snapshotPath: string;
195
+ private _counters;
196
+ private _dirty;
197
+ private _updateSnapshot;
198
+ private _snapshotData;
199
+ private _initialData;
200
+ private _inlineSnapshots;
201
+ private _inlineSnapshotStacks;
202
+ private _testIdToKeys;
203
+ private _rawSnapshots;
204
+ private _uncheckedKeys;
205
+ private _snapshotFormat;
206
+ private _environment;
207
+ private _fileExists;
208
+ expand: boolean;
209
+ private _added;
210
+ private _matched;
211
+ private _unmatched;
212
+ private _updated;
213
+ get added(): CounterMap<string>;
214
+ set added(value: number);
215
+ get matched(): CounterMap<string>;
216
+ set matched(value: number);
217
+ get unmatched(): CounterMap<string>;
218
+ set unmatched(value: number);
219
+ get updated(): CounterMap<string>;
220
+ set updated(value: number);
221
+ private constructor();
222
+ static create(testFilePath: string, options: SnapshotStateOptions): Promise<SnapshotState>;
223
+ get snapshotUpdateState(): SnapshotUpdateState;
224
+ get environment(): SnapshotEnvironment;
225
+ markSnapshotsAsCheckedForTest(testName: string): void;
226
+ clearTest(testId: string): void;
227
+ protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null;
228
+ private _addSnapshot;
229
+ private _resolveKey;
230
+ private _resolveInlineStack;
231
+ private _reconcile;
232
+ save(): Promise<SaveStatus>;
233
+ getUncheckedCount(): number;
234
+ getUncheckedKeys(): Array<string>;
235
+ removeUncheckedKeys(): void;
236
+ probeExpectedSnapshot(options: Pick<SnapshotMatchOptions, "testName" | "testId" | "isInline" | "inlineSnapshot">): ExpectedSnapshot;
237
+ match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot, assertionName }: SnapshotMatchOptions): SnapshotReturnOptions;
238
+ processDomainSnapshot({ testId, received, expectedSnapshot, matchResult, isInline, error, assertionName }: ProcessDomainSnapshotOptions): SnapshotReturnOptions;
239
+ pack(): Promise<SnapshotResult>;
240
+ }
241
+
242
+ type SnapshotData = Record<string, string>;
243
+ type SnapshotUpdateState = "all" | "new" | "none";
244
+ type SnapshotSerializer = Plugin;
245
+ interface SnapshotStateOptions {
246
+ updateSnapshot: SnapshotUpdateState;
247
+ snapshotEnvironment: SnapshotEnvironment;
248
+ expand?: boolean;
249
+ snapshotFormat?: OptionsReceived;
250
+ resolveSnapshotPath?: (path: string, extension: string, context?: any) => string;
251
+ }
252
+ interface SnapshotMatchOptions {
253
+ testId: string;
254
+ testName: string;
255
+ received: unknown;
256
+ key?: string;
257
+ inlineSnapshot?: string;
258
+ isInline: boolean;
259
+ error?: Error;
260
+ rawSnapshot?: RawSnapshotInfo;
261
+ assertionName?: string;
262
+ }
263
+ interface ProcessDomainSnapshotOptions {
264
+ testId: string;
265
+ received: string;
266
+ expectedSnapshot: ExpectedSnapshot;
267
+ matchResult?: DomainMatchResult;
268
+ isInline?: boolean;
269
+ assertionName?: string;
270
+ error?: Error;
271
+ }
272
+ interface SnapshotResult {
273
+ filepath: string;
274
+ added: number;
275
+ fileDeleted: boolean;
276
+ matched: number;
277
+ unchecked: number;
278
+ uncheckedKeys: Array<string>;
279
+ unmatched: number;
280
+ updated: number;
281
+ }
282
+ interface UncheckedSnapshot {
283
+ filePath: string;
284
+ keys: Array<string>;
285
+ }
286
+ interface SnapshotSummary {
287
+ added: number;
288
+ didUpdate: boolean;
289
+ failure: boolean;
290
+ filesAdded: number;
291
+ filesRemoved: number;
292
+ filesRemovedList: Array<string>;
293
+ filesUnmatched: number;
294
+ filesUpdated: number;
295
+ matched: number;
296
+ total: number;
297
+ unchecked: number;
298
+ uncheckedKeysByFile: Array<UncheckedSnapshot>;
299
+ unmatched: number;
300
+ updated: number;
301
+ }
302
+
303
+ interface RawSnapshotInfo {
304
+ file: string;
305
+ readonly?: boolean;
306
+ content?: string;
307
+ }
308
+
309
+ interface AfterSuiteRunMeta {
310
+ coverage?: unknown;
311
+ testFiles: string[];
312
+ environment: string;
313
+ projectName?: string;
314
+ }
315
+ interface UserConsoleLog {
316
+ content: string;
317
+ origin?: string;
318
+ browser?: boolean;
319
+ type: "stdout" | "stderr";
320
+ taskId?: string;
321
+ time: number;
322
+ size: number;
323
+ }
324
+ interface ModuleGraphData {
325
+ graph: Record<string, string[]>;
326
+ externalized: string[];
327
+ inlined: string[];
328
+ }
329
+ interface ProvidedContext {}
330
+ interface ResolveFunctionResult {
331
+ id: string;
332
+ file: string;
333
+ url: string;
334
+ }
335
+ interface FetchCachedFileSystemResult {
336
+ cached: true;
337
+ tmp: string;
338
+ id: string;
339
+ file: string | null;
340
+ url: string;
341
+ invalidate: boolean;
342
+ }
343
+ type LabelColor = "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white";
344
+ interface AsyncLeak {
345
+ filename: string;
346
+ projectName: string;
347
+ stack: string;
348
+ type: string;
349
+ }
350
+
351
+ interface AsymmetricMatcherInterface {
352
+ asymmetricMatch: (other: unknown, customTesters?: Array<Tester>) => boolean;
353
+ toString: () => string;
354
+ getExpectedType?: () => string;
355
+ toAsymmetricMatcher?: () => string;
356
+ }
357
+ declare abstract class AsymmetricMatcher<
358
+ T,
359
+ State extends MatcherState = MatcherState
360
+ > implements AsymmetricMatcherInterface {
361
+ protected sample: T;
362
+ protected inverse: boolean;
363
+ $$typeof: symbol;
364
+ constructor(sample: T, inverse?: boolean);
365
+ protected getMatcherContext(expect?: Chai.ExpectStatic): State;
366
+ abstract asymmetricMatch(other: unknown, customTesters?: Array<Tester>): boolean;
367
+ abstract toString(): string;
368
+ getExpectedType?(): string;
369
+ toAsymmetricMatcher?(): string;
370
+ }
371
+
372
+ declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string;
373
+ declare function printReceived(object: unknown): string;
374
+ declare function printExpected(value: unknown): string;
375
+ declare function getMatcherUtils(): {
376
+ EXPECTED_COLOR: Formatter;
377
+ RECEIVED_COLOR: Formatter;
378
+ INVERTED_COLOR: Formatter;
379
+ BOLD_WEIGHT: Formatter;
380
+ DIM_COLOR: Formatter;
381
+ diff: typeof diff;
382
+ matcherHint: typeof matcherHint;
383
+ printReceived: typeof printReceived;
384
+ printExpected: typeof printExpected;
385
+ printDiffOrStringify: typeof printDiffOrStringify;
386
+ printWithType: typeof printWithType;
387
+ };
388
+ declare function printWithType<T>(name: string, value: T, print: (value: T) => string): string;
389
+ type Tester = (this: TesterContext, a: any, b: any, customTesters: Array<Tester>) => boolean | undefined;
390
+ interface TesterContext {
391
+ equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
392
+ }
393
+
394
+ interface MatcherHintOptions {
395
+ comment?: string;
396
+ expectedColor?: Formatter;
397
+ isDirectExpectCall?: boolean;
398
+ isNot?: boolean;
399
+ promise?: string;
400
+ receivedColor?: Formatter;
401
+ secondArgument?: string;
402
+ secondArgumentColor?: Formatter;
403
+ }
404
+ interface MatcherState {
405
+ customTesters: Array<Tester>;
406
+ assertionCalls: number;
407
+ currentTestName?: string;
408
+ /**
409
+ * @deprecated exists only in types
410
+ */
411
+ dontThrow?: () => void;
412
+ /**
413
+ * @deprecated exists only in types
414
+ */
415
+ error?: Error;
416
+ equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
417
+ /**
418
+ * @deprecated exists only in types
419
+ */
420
+ expand?: boolean;
421
+ expectedAssertionsNumber?: number | null;
422
+ expectedAssertionsNumberErrorGen?: (() => Error) | null;
423
+ isExpectingAssertions?: boolean;
424
+ isExpectingAssertionsError?: Error | null;
425
+ isNot: boolean;
426
+ promise: string;
427
+ /**
428
+ * @deprecated exists only in types
429
+ */
430
+ suppressedErrors: Array<Error>;
431
+ testPath?: string;
432
+ utils: ReturnType<typeof getMatcherUtils> & {
433
+ diff: typeof diff;
434
+ stringify: typeof stringify;
435
+ iterableEquality: Tester;
436
+ subsetEquality: Tester;
437
+ };
438
+ soft?: boolean;
439
+ poll?: boolean;
440
+ /**
441
+ * The same assertion instance that chai plugins receive.
442
+ * @experimental
443
+ * @see {@link https://www.chaijs.com/guide/plugins/} Core Plugin Concepts
444
+ */
445
+ readonly assertion: Assertion;
446
+ }
447
+ interface SyncExpectationResult {
448
+ pass: boolean;
449
+ message: () => string;
450
+ actual?: any;
451
+ expected?: any;
452
+ meta?: object;
453
+ }
454
+ type AsyncExpectationResult = Promise<SyncExpectationResult>;
455
+ type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
456
+ interface RawMatcherFn<
457
+ T extends MatcherState = MatcherState,
458
+ E extends Array<any> = Array<any>
459
+ > {
460
+ (this: T, received: any, ...expected: E): ExpectationResult;
461
+ }
462
+ interface Matchers<T = any> {}
463
+ type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>> & ThisType<T> & { [K in keyof Matchers<T>]? : RawMatcherFn<T, Parameters<Matchers<T>[K]>> };
464
+ interface ExpectStatic extends Chai.ExpectStatic, Matchers, AsymmetricMatchersContaining {
465
+ <T>(actual: T, message?: string): Assertion<T>;
466
+ extend: (expects: MatchersObject) => void;
467
+ anything: () => any;
468
+ any: (constructor: unknown) => any;
469
+ getState: () => MatcherState;
470
+ setState: (state: Partial<MatcherState>) => void;
471
+ not: AsymmetricMatchersContaining;
472
+ }
473
+ interface CustomMatcher {
474
+ /**
475
+ * Checks that a value satisfies a custom matcher function.
476
+ *
477
+ * @param matcher - A function returning a boolean based on the custom condition
478
+ * @param message - Optional custom error message on failure
479
+ *
480
+ * @example
481
+ * expect(age).toSatisfy(val => val >= 18, 'Age must be at least 18');
482
+ * expect(age).toEqual(expect.toSatisfy(val => val >= 18, 'Age must be at least 18'));
483
+ */
484
+ toSatisfy: (matcher: (value: any) => boolean, message?: string) => any;
485
+ /**
486
+ * Matches if the received value is one of the values in the expected array or set.
487
+ *
488
+ * @example
489
+ * expect(1).toBeOneOf([1, 2, 3])
490
+ * expect('foo').toBeOneOf([expect.any(String)])
491
+ * expect({ a: 1 }).toEqual({ a: expect.toBeOneOf(['1', '2', '3']) })
492
+ */
493
+ toBeOneOf: <T>(sample: ReadonlyArray<T> | ReadonlySet<T>) => any;
494
+ }
495
+ interface AsymmetricMatchersContaining extends CustomMatcher {
496
+ /**
497
+ * Matches if the received string contains the expected substring.
498
+ *
499
+ * @example
500
+ * expect('I have an apple').toEqual(expect.stringContaining('apple'));
501
+ * expect({ a: 'test string' }).toEqual({ a: expect.stringContaining('test') });
502
+ */
503
+ stringContaining: (expected: string) => any;
504
+ /**
505
+ * Matches if the received object contains all properties of the expected object.
506
+ *
507
+ * @example
508
+ * expect({ a: '1', b: 2 }).toEqual(expect.objectContaining({ a: '1' }))
509
+ */
510
+ objectContaining: <T = any>(expected: DeeplyAllowMatchers<T>) => any;
511
+ /**
512
+ * Matches if the received array contains all elements in the expected array.
513
+ *
514
+ * @example
515
+ * expect(['a', 'b', 'c']).toEqual(expect.arrayContaining(['b', 'a']));
516
+ */
517
+ arrayContaining: <T = unknown>(expected: Array<DeeplyAllowMatchers<T>>) => any;
518
+ /**
519
+ * Matches if the received string or regex matches the expected pattern.
520
+ *
521
+ * @example
522
+ * expect('hello world').toEqual(expect.stringMatching(/^hello/));
523
+ * expect('hello world').toEqual(expect.stringMatching('hello'));
524
+ */
525
+ stringMatching: (expected: string | RegExp) => any;
526
+ /**
527
+ * Matches if the received number is within a certain precision of the expected number.
528
+ *
529
+ * @example
530
+ * expect(10.45).toEqual(expect.closeTo(10.5, 1));
531
+ * expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision
532
+ */
533
+ closeTo: (expected: number, precision?: number) => any;
534
+ /**
535
+ * Matches if the received value validates against a Standard Schema.
536
+ *
537
+ * @param schema - A Standard Schema V1 compatible schema object
538
+ *
539
+ * @example
540
+ * expect(user).toEqual(expect.schemaMatching(z.object({ name: z.string() })))
541
+ * expect(['hello', 'world']).toEqual([expect.schemaMatching(z.string()), expect.schemaMatching(z.string())])
542
+ */
543
+ schemaMatching: (schema: unknown) => any;
544
+ }
545
+ type WithAsymmetricMatcher<T> = T | AsymmetricMatcher<unknown>;
546
+ type DeeplyAllowMatchers<T> = T extends Array<infer Element> ? WithAsymmetricMatcher<T> | DeeplyAllowMatchers<Element>[] : T extends object ? WithAsymmetricMatcher<T> | { [K in keyof T] : DeeplyAllowMatchers<T[K]> } : WithAsymmetricMatcher<T>;
547
+ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
548
+ /**
549
+ * Used when you want to check that two objects have the same value.
550
+ * This matcher recursively checks the equality of all fields, rather than checking for object identity.
551
+ *
552
+ * @example
553
+ * expect(user).toEqual({ name: 'Alice', age: 30 });
554
+ */
555
+ toEqual: <E>(expected: E) => void;
556
+ /**
557
+ * Use to test that objects have the same types as well as structure.
558
+ *
559
+ * @example
560
+ * expect(user).toStrictEqual({ name: 'Alice', age: 30 });
561
+ */
562
+ toStrictEqual: <E>(expected: E) => void;
563
+ /**
564
+ * Checks that a value is what you expect. It calls `Object.is` to compare values.
565
+ * Don't use `toBe` with floating-point numbers.
566
+ *
567
+ * @example
568
+ * expect(result).toBe(42);
569
+ * expect(status).toBe(true);
570
+ */
571
+ toBe: <E>(expected: E) => void;
572
+ /**
573
+ * Check that a string matches a regular expression.
574
+ *
575
+ * @example
576
+ * expect(message).toMatch(/hello/);
577
+ * expect(greeting).toMatch('world');
578
+ */
579
+ toMatch: (expected: string | RegExp) => void;
580
+ /**
581
+ * Used to check that a JavaScript object matches a subset of the properties of an object
582
+ *
583
+ * @example
584
+ * expect(user).toMatchObject({
585
+ * name: 'Alice',
586
+ * address: { city: 'Wonderland' }
587
+ * });
588
+ */
589
+ toMatchObject: <E extends object | any[]>(expected: E) => void;
590
+ /**
591
+ * Used when you want to check that an item is in a list.
592
+ * For testing the items in the list, this uses `===`, a strict equality check.
593
+ *
594
+ * @example
595
+ * expect(items).toContain('apple');
596
+ * expect(numbers).toContain(5);
597
+ */
598
+ toContain: <E>(item: E) => void;
599
+ /**
600
+ * Used when you want to check that an item is in a list.
601
+ * For testing the items in the list, this matcher recursively checks the
602
+ * equality of all fields, rather than checking for object identity.
603
+ *
604
+ * @example
605
+ * expect(items).toContainEqual({ name: 'apple', quantity: 1 });
606
+ */
607
+ toContainEqual: <E>(item: E) => void;
608
+ /**
609
+ * Use when you don't care what a value is, you just want to ensure a value
610
+ * is true in a boolean context. In JavaScript, there are six falsy values:
611
+ * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy.
612
+ *
613
+ * @example
614
+ * expect(user.isActive).toBeTruthy();
615
+ */
616
+ toBeTruthy: () => void;
617
+ /**
618
+ * When you don't care what a value is, you just want to
619
+ * ensure a value is false in a boolean context.
620
+ *
621
+ * @example
622
+ * expect(user.isActive).toBeFalsy();
623
+ */
624
+ toBeFalsy: () => void;
625
+ /**
626
+ * For comparing floating point numbers.
627
+ *
628
+ * @example
629
+ * expect(score).toBeGreaterThan(10);
630
+ */
631
+ toBeGreaterThan: (num: number | bigint) => void;
632
+ /**
633
+ * For comparing floating point numbers.
634
+ *
635
+ * @example
636
+ * expect(score).toBeGreaterThanOrEqual(10);
637
+ */
638
+ toBeGreaterThanOrEqual: (num: number | bigint) => void;
639
+ /**
640
+ * For comparing floating point numbers.
641
+ *
642
+ * @example
643
+ * expect(score).toBeLessThan(10);
644
+ */
645
+ toBeLessThan: (num: number | bigint) => void;
646
+ /**
647
+ * For comparing floating point numbers.
648
+ *
649
+ * @example
650
+ * expect(score).toBeLessThanOrEqual(10);
651
+ */
652
+ toBeLessThanOrEqual: (num: number | bigint) => void;
653
+ /**
654
+ * Used to check that a variable is NaN.
655
+ *
656
+ * @example
657
+ * expect(value).toBeNaN();
658
+ */
659
+ toBeNaN: () => void;
660
+ /**
661
+ * Used to check that a variable is undefined.
662
+ *
663
+ * @example
664
+ * expect(value).toBeUndefined();
665
+ */
666
+ toBeUndefined: () => void;
667
+ /**
668
+ * This is the same as `.toBe(null)` but the error messages are a bit nicer.
669
+ * So use `.toBeNull()` when you want to check that something is null.
670
+ *
671
+ * @example
672
+ * expect(value).toBeNull();
673
+ */
674
+ toBeNull: () => void;
675
+ /**
676
+ * Used to check that a variable is nullable (null or undefined).
677
+ *
678
+ * @example
679
+ * expect(value).toBeNullable();
680
+ */
681
+ toBeNullable: () => void;
682
+ /**
683
+ * Ensure that a variable is not undefined.
684
+ *
685
+ * @example
686
+ * expect(value).toBeDefined();
687
+ */
688
+ toBeDefined: () => void;
689
+ /**
690
+ * Ensure that an object is an instance of a class.
691
+ * This matcher uses `instanceof` underneath.
692
+ *
693
+ * @example
694
+ * expect(new Date()).toBeInstanceOf(Date);
695
+ */
696
+ toBeInstanceOf: <E>(expected: E) => void;
697
+ /**
698
+ * Used to check that an object has a `.length` property
699
+ * and it is set to a certain numeric value.
700
+ *
701
+ * @example
702
+ * expect([1, 2, 3]).toHaveLength(3);
703
+ * expect('hello').toHaveLength(5);
704
+ */
705
+ toHaveLength: (length: number) => void;
706
+ /**
707
+ * Use to check if a property at the specified path exists on an object.
708
+ * For checking deeply nested properties, you may use dot notation or an array containing
709
+ * the path segments for deep references.
710
+ *
711
+ * Optionally, you can provide a value to check if it matches the value present at the path
712
+ * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks
713
+ * the equality of all fields.
714
+ *
715
+ * @example
716
+ * expect(user).toHaveProperty('address.city', 'New York');
717
+ * expect(config).toHaveProperty(['settings', 'theme'], 'dark');
718
+ */
719
+ toHaveProperty: <E>(property: string | (string | number)[], value?: E) => void;
720
+ /**
721
+ * Using exact equality with floating point numbers is a bad idea.
722
+ * Rounding means that intuitive things fail.
723
+ * The default for `numDigits` is 2.
724
+ *
725
+ * @example
726
+ * expect(price).toBeCloseTo(9.99, 2);
727
+ */
728
+ toBeCloseTo: (number: number, numDigits?: number) => void;
729
+ /**
730
+ * Ensures that a mock function is called an exact number of times.
731
+ *
732
+ * Also under the alias `expect.toBeCalledTimes`.
733
+ *
734
+ * @example
735
+ * expect(mockFunc).toHaveBeenCalledTimes(2);
736
+ */
737
+ toHaveBeenCalledTimes: (times: number) => void;
738
+ /**
739
+ * Ensures that a mock function is called an exact number of times.
740
+ *
741
+ * Alias for `expect.toHaveBeenCalledTimes`.
742
+ *
743
+ * @example
744
+ * expect(mockFunc).toBeCalledTimes(2);
745
+ * @deprecated Use `toHaveBeenCalledTimes` instead
746
+ */
747
+ toBeCalledTimes: (times: number) => void;
748
+ /**
749
+ * Ensures that a mock function is called.
750
+ *
751
+ * Also under the alias `expect.toBeCalled`.
752
+ *
753
+ * @example
754
+ * expect(mockFunc).toHaveBeenCalled();
755
+ */
756
+ toHaveBeenCalled: () => void;
757
+ /**
758
+ * Ensures that a mock function is called.
759
+ *
760
+ * Alias for `expect.toHaveBeenCalled`.
761
+ *
762
+ * @example
763
+ * expect(mockFunc).toBeCalled();
764
+ * @deprecated Use `toHaveBeenCalled` instead
765
+ */
766
+ toBeCalled: () => void;
767
+ /**
768
+ * Ensure that a mock function is called with specific arguments.
769
+ *
770
+ * Also under the alias `expect.toBeCalledWith`.
771
+ *
772
+ * @example
773
+ * expect(mockFunc).toHaveBeenCalledWith('arg1', 42);
774
+ */
775
+ toHaveBeenCalledWith: <E extends any[]>(...args: E) => void;
776
+ /**
777
+ * Ensure that a mock function is called with specific arguments.
778
+ *
779
+ * Alias for `expect.toHaveBeenCalledWith`.
780
+ *
781
+ * @example
782
+ * expect(mockFunc).toBeCalledWith('arg1', 42);
783
+ * @deprecated Use `toHaveBeenCalledWith` instead
784
+ */
785
+ toBeCalledWith: <E extends any[]>(...args: E) => void;
786
+ /**
787
+ * Ensure that a mock function is called with specific arguments on an Nth call.
788
+ *
789
+ * Also under the alias `expect.nthCalledWith`.
790
+ *
791
+ * @example
792
+ * expect(mockFunc).toHaveBeenNthCalledWith(2, 'secondArg');
793
+ */
794
+ toHaveBeenNthCalledWith: <E extends any[]>(n: number, ...args: E) => void;
795
+ /**
796
+ * If you have a mock function, you can use `.toHaveBeenLastCalledWith`
797
+ * to test what arguments it was last called with.
798
+ *
799
+ * Also under the alias `expect.lastCalledWith`.
800
+ *
801
+ * @example
802
+ * expect(mockFunc).toHaveBeenLastCalledWith('lastArg');
803
+ */
804
+ toHaveBeenLastCalledWith: <E extends any[]>(...args: E) => void;
805
+ /**
806
+ * Used to test that a function throws when it is called.
807
+ *
808
+ * Also under the alias `expect.toThrowError`.
809
+ *
810
+ * @example
811
+ * expect(() => functionWithError()).toThrow('Error message');
812
+ * expect(() => parseJSON('invalid')).toThrow(SyntaxError);
813
+ * expect(() => { throw 42 }).toThrow(42);
814
+ */
815
+ toThrow: (expected?: any) => void;
816
+ /**
817
+ * Used to test that a function throws when it is called.
818
+ *
819
+ * Alias for `expect.toThrow`.
820
+ *
821
+ * @example
822
+ * expect(() => functionWithError()).toThrowError('Error message');
823
+ * expect(() => parseJSON('invalid')).toThrowError(SyntaxError);
824
+ * expect(() => { throw 42 }).toThrowError(42);
825
+ * @deprecated Use `toThrow` instead
826
+ */
827
+ toThrowError: (expected?: any) => void;
828
+ /**
829
+ * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
830
+ *
831
+ * Alias for `expect.toHaveReturned`.
832
+ *
833
+ * @example
834
+ * expect(mockFunc).toReturn();
835
+ * @deprecated Use `toHaveReturned` instead
836
+ */
837
+ toReturn: () => void;
838
+ /**
839
+ * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
840
+ *
841
+ * Also under the alias `expect.toReturn`.
842
+ *
843
+ * @example
844
+ * expect(mockFunc).toHaveReturned();
845
+ */
846
+ toHaveReturned: () => void;
847
+ /**
848
+ * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
849
+ * Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
850
+ *
851
+ * Alias for `expect.toHaveReturnedTimes`.
852
+ *
853
+ * @example
854
+ * expect(mockFunc).toReturnTimes(3);
855
+ * @deprecated Use `toHaveReturnedTimes` instead
856
+ */
857
+ toReturnTimes: (times: number) => void;
858
+ /**
859
+ * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
860
+ * Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
861
+ *
862
+ * Also under the alias `expect.toReturnTimes`.
863
+ *
864
+ * @example
865
+ * expect(mockFunc).toHaveReturnedTimes(3);
866
+ */
867
+ toHaveReturnedTimes: (times: number) => void;
868
+ /**
869
+ * Use to ensure that a mock function returned a specific value.
870
+ *
871
+ * Alias for `expect.toHaveReturnedWith`.
872
+ *
873
+ * @example
874
+ * expect(mockFunc).toReturnWith('returnValue');
875
+ * @deprecated Use `toHaveReturnedWith` instead
876
+ */
877
+ toReturnWith: <E>(value: E) => void;
878
+ /**
879
+ * Use to ensure that a mock function returned a specific value.
880
+ *
881
+ * Also under the alias `expect.toReturnWith`.
882
+ *
883
+ * @example
884
+ * expect(mockFunc).toHaveReturnedWith('returnValue');
885
+ */
886
+ toHaveReturnedWith: <E>(value: E) => void;
887
+ /**
888
+ * Use to test the specific value that a mock function last returned.
889
+ * If the last call to the mock function threw an error, then this matcher will fail
890
+ * no matter what value you provided as the expected return value.
891
+ *
892
+ * Also under the alias `expect.lastReturnedWith`.
893
+ *
894
+ * @example
895
+ * expect(mockFunc).toHaveLastReturnedWith('lastValue');
896
+ */
897
+ toHaveLastReturnedWith: <E>(value: E) => void;
898
+ /**
899
+ * Use to test the specific value that a mock function returned for the nth call.
900
+ * If the nth call to the mock function threw an error, then this matcher will fail
901
+ * no matter what value you provided as the expected return value.
902
+ *
903
+ * Also under the alias `expect.nthReturnedWith`.
904
+ *
905
+ * @example
906
+ * expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue');
907
+ */
908
+ toHaveNthReturnedWith: <E>(nthCall: number, value: E) => void;
909
+ }
910
+ type VitestAssertion<
911
+ A,
912
+ T
913
+ > = { [K in keyof A] : A[K] extends Chai.Assertion ? Assertion<T> : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion<A[K], T> } & ((type: string, message?: string) => Assertion);
914
+ type Promisify<O> = { [K in keyof O] : O[K] extends (...args: infer A) => infer R ? Promisify<O[K]> & ((...args: A) => Promise<R>) : O[K] };
915
+ type PromisifyAssertion<T> = Promisify<Assertion<T>>;
916
+ interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T>, ChaiMockAssertion, Matchers<T> {
917
+ /**
918
+ * Ensures a value is of a specific type.
919
+ *
920
+ * @example
921
+ * expect(value).toBeTypeOf('string');
922
+ * expect(number).toBeTypeOf('number');
923
+ */
924
+ toBeTypeOf: (expected: "bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol" | "undefined") => void;
925
+ /**
926
+ * Asserts that a mock function was called exactly once.
927
+ *
928
+ * @example
929
+ * expect(mockFunc).toHaveBeenCalledOnce();
930
+ */
931
+ toHaveBeenCalledOnce: () => void;
932
+ /**
933
+ * Ensure that a mock function is called with specific arguments and called
934
+ * exactly once.
935
+ *
936
+ * @example
937
+ * expect(mockFunc).toHaveBeenCalledExactlyOnceWith('arg1', 42);
938
+ */
939
+ toHaveBeenCalledExactlyOnceWith: <E extends any[]>(...args: E) => void;
940
+ /**
941
+ * This assertion checks if a `Mock` was called before another `Mock`.
942
+ * @param mock - A mock function created by `vi.spyOn` or `vi.fn`
943
+ * @param failIfNoFirstInvocation - Fail if the first mock was never called
944
+ * @example
945
+ * const mock1 = vi.fn()
946
+ * const mock2 = vi.fn()
947
+ *
948
+ * mock1()
949
+ * mock2()
950
+ * mock1()
951
+ *
952
+ * expect(mock1).toHaveBeenCalledBefore(mock2)
953
+ */
954
+ toHaveBeenCalledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
955
+ /**
956
+ * This assertion checks if a `Mock` was called after another `Mock`.
957
+ * @param mock - A mock function created by `vi.spyOn` or `vi.fn`
958
+ * @param failIfNoFirstInvocation - Fail if the first mock was never called
959
+ * @example
960
+ * const mock1 = vi.fn()
961
+ * const mock2 = vi.fn()
962
+ *
963
+ * mock2()
964
+ * mock1()
965
+ * mock2()
966
+ *
967
+ * expect(mock1).toHaveBeenCalledAfter(mock2)
968
+ */
969
+ toHaveBeenCalledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
970
+ /**
971
+ * Checks that a promise resolves successfully at least once.
972
+ *
973
+ * @example
974
+ * await expect(promise).toHaveResolved();
975
+ */
976
+ toHaveResolved: () => void;
977
+ /**
978
+ * Checks that a promise resolves to a specific value.
979
+ *
980
+ * @example
981
+ * await expect(promise).toHaveResolvedWith('success');
982
+ */
983
+ toHaveResolvedWith: <E>(value: E) => void;
984
+ /**
985
+ * Ensures a promise resolves a specific number of times.
986
+ *
987
+ * @example
988
+ * expect(mockAsyncFunc).toHaveResolvedTimes(3);
989
+ */
990
+ toHaveResolvedTimes: (times: number) => void;
991
+ /**
992
+ * Asserts that the last resolved value of a promise matches an expected value.
993
+ *
994
+ * @example
995
+ * await expect(mockAsyncFunc).toHaveLastResolvedWith('finalResult');
996
+ */
997
+ toHaveLastResolvedWith: <E>(value: E) => void;
998
+ /**
999
+ * Ensures a specific value was returned by a promise on the nth resolution.
1000
+ *
1001
+ * @example
1002
+ * await expect(mockAsyncFunc).toHaveNthResolvedWith(2, 'secondResult');
1003
+ */
1004
+ toHaveNthResolvedWith: <E>(nthCall: number, value: E) => void;
1005
+ /**
1006
+ * Verifies that a promise resolves.
1007
+ *
1008
+ * @example
1009
+ * await expect(someAsyncFunc).resolves.toBe(42);
1010
+ */
1011
+ resolves: PromisifyAssertion<T>;
1012
+ /**
1013
+ * Verifies that a promise rejects.
1014
+ *
1015
+ * @example
1016
+ * await expect(someAsyncFunc).rejects.toThrow('error');
1017
+ */
1018
+ rejects: PromisifyAssertion<T>;
1019
+ }
1020
+ /**
1021
+ * Chai-style assertions for spy/mock testing.
1022
+ * These provide sinon-chai compatible assertion names that delegate to Jest-style implementations.
1023
+ */
1024
+ interface ChaiMockAssertion {
1025
+ /**
1026
+ * Checks that a spy was called at least once.
1027
+ * Chai-style equivalent of `toHaveBeenCalled`.
1028
+ *
1029
+ * @example
1030
+ * expect(spy).to.have.been.called
1031
+ */
1032
+ readonly called: Assertion;
1033
+ /**
1034
+ * Checks that a spy was called a specific number of times.
1035
+ * Chai-style equivalent of `toHaveBeenCalledTimes`.
1036
+ *
1037
+ * @example
1038
+ * expect(spy).to.have.callCount(3)
1039
+ */
1040
+ callCount: (count: number) => void;
1041
+ /**
1042
+ * Checks that a spy was called with specific arguments at least once.
1043
+ * Chai-style equivalent of `toHaveBeenCalledWith`.
1044
+ *
1045
+ * @example
1046
+ * expect(spy).to.have.been.calledWith('arg1', 'arg2')
1047
+ */
1048
+ calledWith: <E extends any[]>(...args: E) => void;
1049
+ /**
1050
+ * Checks that a spy was called exactly once.
1051
+ * Chai-style equivalent of `toHaveBeenCalledOnce`.
1052
+ *
1053
+ * @example
1054
+ * expect(spy).to.have.been.calledOnce
1055
+ */
1056
+ readonly calledOnce: Assertion;
1057
+ /**
1058
+ * Checks that a spy was called exactly once with specific arguments.
1059
+ * Chai-style equivalent of `toHaveBeenCalledExactlyOnceWith`.
1060
+ *
1061
+ * @example
1062
+ * expect(spy).to.have.been.calledOnceWith('arg1', 'arg2')
1063
+ */
1064
+ calledOnceWith: <E extends any[]>(...args: E) => void;
1065
+ /**
1066
+ * Checks that the last call to a spy was made with specific arguments.
1067
+ * Chai-style equivalent of `toHaveBeenLastCalledWith`.
1068
+ *
1069
+ * @example
1070
+ * expect(spy).to.have.been.lastCalledWith('arg1', 'arg2')
1071
+ */
1072
+ lastCalledWith: <E extends any[]>(...args: E) => void;
1073
+ /**
1074
+ * Checks that the nth call to a spy was made with specific arguments.
1075
+ * Chai-style equivalent of `toHaveBeenNthCalledWith`.
1076
+ *
1077
+ * @example
1078
+ * expect(spy).to.have.been.nthCalledWith(2, 'arg1', 'arg2')
1079
+ */
1080
+ nthCalledWith: <E extends any[]>(n: number, ...args: E) => void;
1081
+ /**
1082
+ * Checks that a spy returned a specific value at least once.
1083
+ * Chai-style equivalent of `toHaveReturnedWith`.
1084
+ *
1085
+ * @example
1086
+ * expect(spy).to.have.returned('value')
1087
+ */
1088
+ returned: <E>(value: E) => void;
1089
+ /**
1090
+ * Checks that a spy returned a specific value at least once.
1091
+ * Chai-style equivalent of `toHaveReturnedWith`.
1092
+ *
1093
+ * @example
1094
+ * expect(spy).to.have.returnedWith('value')
1095
+ */
1096
+ returnedWith: <E>(value: E) => void;
1097
+ /**
1098
+ * Checks that a spy returned successfully a specific number of times.
1099
+ * Chai-style equivalent of `toHaveReturnedTimes`.
1100
+ *
1101
+ * @example
1102
+ * expect(spy).to.have.returnedTimes(3)
1103
+ */
1104
+ returnedTimes: (count: number) => void;
1105
+ /**
1106
+ * Checks that the last return value of a spy matches the expected value.
1107
+ * Chai-style equivalent of `toHaveLastReturnedWith`.
1108
+ *
1109
+ * @example
1110
+ * expect(spy).to.have.lastReturnedWith('value')
1111
+ */
1112
+ lastReturnedWith: <E>(value: E) => void;
1113
+ /**
1114
+ * Checks that the nth return value of a spy matches the expected value.
1115
+ * Chai-style equivalent of `toHaveNthReturnedWith`.
1116
+ *
1117
+ * @example
1118
+ * expect(spy).to.have.nthReturnedWith(2, 'value')
1119
+ */
1120
+ nthReturnedWith: <E>(n: number, value: E) => void;
1121
+ /**
1122
+ * Checks that a spy was called before another spy.
1123
+ * Chai-style equivalent of `toHaveBeenCalledBefore`.
1124
+ *
1125
+ * @example
1126
+ * expect(spy1).to.have.been.calledBefore(spy2)
1127
+ */
1128
+ calledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
1129
+ /**
1130
+ * Checks that a spy was called after another spy.
1131
+ * Chai-style equivalent of `toHaveBeenCalledAfter`.
1132
+ *
1133
+ * @example
1134
+ * expect(spy1).to.have.been.calledAfter(spy2)
1135
+ */
1136
+ calledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
1137
+ /**
1138
+ * Checks that a spy was called exactly twice.
1139
+ * Chai-style equivalent of `toHaveBeenCalledTimes(2)`.
1140
+ *
1141
+ * @example
1142
+ * expect(spy).to.have.been.calledTwice
1143
+ */
1144
+ readonly calledTwice: Assertion;
1145
+ /**
1146
+ * Checks that a spy was called exactly three times.
1147
+ * Chai-style equivalent of `toHaveBeenCalledTimes(3)`.
1148
+ *
1149
+ * @example
1150
+ * expect(spy).to.have.been.calledThrice
1151
+ */
1152
+ readonly calledThrice: Assertion;
1153
+ }
1154
+ declare global {
1155
+ namespace jest {
1156
+ interface Matchers<
1157
+ R,
1158
+ T = {}
1159
+ > {}
1160
+ }
1161
+ }
1162
+
1163
+ type ExtractBenchNames<T extends BenchRegistration<any>[]> = Exclude<{ [K in keyof T] : T[K] extends BenchRegistration<infer N> ? N : never }[number], never>;
1164
+ type BenchResult = TaskResultCompleted & TaskResultRuntimeInfo & TaskResultTimestampProviderInfo;
1165
+ interface BenchStorage<T extends string> {
1166
+ get: (name: T) => BenchResult;
1167
+ }
1168
+
1169
+ /**
1170
+ * Options accepted by `bench(name, options, fn)`. Extends tinybench's
1171
+ * `FnOptions` with Vitest-specific fields.
1172
+ */
1173
+ interface BenchFnOptions extends FnOptions {
1174
+ /**
1175
+ * Path (relative to the project root) where the benchmark result is written
1176
+ * after a successful run. The string `${projectName}` is substituted with
1177
+ * the current project name. Absolute paths are accepted as long as they
1178
+ * resolve inside the project root.
1179
+ */
1180
+ writeResult?: string;
1181
+ /**
1182
+ * Mark this benchmark as a per-project entry. Per-project tasks still appear
1183
+ * in the inline comparison table for the current run, and Vitest additionally
1184
+ * collects them across projects and prints a single cross-project table at
1185
+ * the end of the run.
1186
+ */
1187
+ perProject?: boolean;
1188
+ }
1189
+ interface BenchRegistration<Name extends string> {
1190
+ name: Name;
1191
+ /**
1192
+ * The benchmark function. Absent for registrations created via `bench.from()`.
1193
+ */
1194
+ fn?: Fn;
1195
+ /**
1196
+ * Per-benchmark options (`beforeEach`, `beforeAll`, etc.). Absent for
1197
+ * registrations created via `bench.from()`.
1198
+ */
1199
+ fnOpts?: FnOptions;
1200
+ run: (options?: BenchOptions) => Promise<BenchResult>;
1201
+ }
1202
+ interface BenchCompare {
1203
+ <Args extends BenchRegistration<any>[]>(...args: Args): Promise<BenchStorage<ExtractBenchNames<Args>>>;
1204
+ <Args extends BenchRegistration<any>[]>(...args: [...Args, BenchOptions]): Promise<BenchStorage<ExtractBenchNames<Args>>>;
1205
+ }
1206
+ interface BenchFactory {
1207
+ <Name extends string>(name: Name | Function, fn: Fn): BenchRegistration<Name>;
1208
+ <Name extends string>(name: Name | Function, options: BenchFnOptions, fn: Fn): BenchRegistration<Name>;
1209
+ }
1210
+ interface BenchFromSource {
1211
+ (): BaselineData | Promise<BaselineData>;
1212
+ }
1213
+ interface BenchFrom {
1214
+ <Name extends string>(name: Name | Function, source: string | BenchFromSource): BenchRegistration<Name>;
1215
+ }
1216
+ interface Bench extends BenchFactory {
1217
+ compare: BenchCompare;
1218
+ from: BenchFrom;
1219
+ }
1220
+
1221
+ interface TestFixtureItem extends FixtureOptions {
1222
+ name: string;
1223
+ value: unknown;
1224
+ scope: "test" | "file" | "worker";
1225
+ deps: Set<string>;
1226
+ parent?: TestFixtureItem;
1227
+ }
1228
+ type UserFixtures = Record<string, unknown>;
1229
+ type FixtureRegistrations = Map<string, TestFixtureItem>;
1230
+ declare class TestFixtures {
1231
+ private _suiteContexts;
1232
+ private _overrides;
1233
+ private _registrations;
1234
+ private static _definitions;
1235
+ private static _builtinFixtures;
1236
+ private static _fixtureOptionKeys;
1237
+ private static _fixtureScopes;
1238
+ private static _workerContextSuite;
1239
+ static clearDefinitions(): void;
1240
+ static getWorkerContexts(): Record<string, any>[];
1241
+ static getFileContexts(file: File): Record<string, any>[];
1242
+ static isFixtureOptions(obj: unknown): boolean;
1243
+ constructor(registrations?: FixtureRegistrations);
1244
+ extend(runner: VitestRunner, userFixtures: UserFixtures): TestFixtures;
1245
+ get(suite: Suite): FixtureRegistrations;
1246
+ override(runner: VitestRunner, userFixtures: UserFixtures): void;
1247
+ getFileContext(file: File): Record<string, any>;
1248
+ getWorkerContext(): Record<string, any>;
1249
+ private parseUserFixtures;
1250
+ }
1251
+
1252
+ /**
1253
+ * Registers a callback function to be executed once before all tests within the current suite.
1254
+ * This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment.
1255
+ *
1256
+ * **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
1257
+ *
1258
+ * @param {Function} fn - The callback function to be executed before all tests.
1259
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1260
+ * @returns {void}
1261
+ * @example
1262
+ * ```ts
1263
+ * // Example of using beforeAll to set up a database connection
1264
+ * beforeAll(async () => {
1265
+ * await database.connect();
1266
+ * });
1267
+ * ```
1268
+ */
1269
+ declare function beforeAll<ExtraContext = object>(this: unknown, fn: BeforeAllListener<ExtraContext>, timeout?: number): void;
1270
+ /**
1271
+ * Registers a callback function to be executed once after all tests within the current suite have completed.
1272
+ * This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files.
1273
+ *
1274
+ * **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1275
+ *
1276
+ * @param {Function} fn - The callback function to be executed after all tests.
1277
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1278
+ * @returns {void}
1279
+ * @example
1280
+ * ```ts
1281
+ * // Example of using afterAll to close a database connection
1282
+ * afterAll(async () => {
1283
+ * await database.disconnect();
1284
+ * });
1285
+ * ```
1286
+ */
1287
+ declare function afterAll<ExtraContext = object>(this: unknown, fn: AfterAllListener<ExtraContext>, timeout?: number): void;
1288
+ /**
1289
+ * Registers a callback function to be executed before each test within the current suite.
1290
+ * This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables.
1291
+ *
1292
+ * **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
1293
+ *
1294
+ * @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
1295
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1296
+ * @returns {void}
1297
+ * @example
1298
+ * ```ts
1299
+ * // Example of using beforeEach to reset a database state
1300
+ * beforeEach(async () => {
1301
+ * await database.reset();
1302
+ * });
1303
+ * ```
1304
+ */
1305
+ declare function beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void;
1306
+ /**
1307
+ * Registers a callback function to be executed after each test within the current suite has completed.
1308
+ * This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions.
1309
+ *
1310
+ * **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1311
+ *
1312
+ * @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
1313
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1314
+ * @returns {void}
1315
+ * @example
1316
+ * ```ts
1317
+ * // Example of using afterEach to delete temporary files created during a test
1318
+ * afterEach(async () => {
1319
+ * await fileSystem.deleteTempFiles();
1320
+ * });
1321
+ * ```
1322
+ */
1323
+ declare function afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void;
1324
+ /**
1325
+ * Registers a callback function to be executed when a test fails within the current suite.
1326
+ * This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
1327
+ *
1328
+ * **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1329
+ *
1330
+ * @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
1331
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1332
+ * @throws {Error} Throws an error if the function is not called within a test.
1333
+ * @returns {void}
1334
+ * @example
1335
+ * ```ts
1336
+ * // Example of using onTestFailed to log failure details
1337
+ * onTestFailed(({ errors }) => {
1338
+ * console.log(`Test failed: ${test.name}`, errors);
1339
+ * });
1340
+ * ```
1341
+ */
1342
+ declare const onTestFailed: TaskHook<OnTestFailedHandler>;
1343
+ /**
1344
+ * Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
1345
+ * This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
1346
+ *
1347
+ * This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`.
1348
+ *
1349
+ * **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1350
+ *
1351
+ * **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
1352
+ *
1353
+ * @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status.
1354
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1355
+ * @throws {Error} Throws an error if the function is not called within a test.
1356
+ * @returns {void}
1357
+ * @example
1358
+ * ```ts
1359
+ * // Example of using onTestFinished for cleanup
1360
+ * const db = await connectToDatabase();
1361
+ * onTestFinished(async () => {
1362
+ * await db.disconnect();
1363
+ * });
1364
+ * ```
1365
+ */
1366
+ declare const onTestFinished: TaskHook<OnTestFinishedHandler>;
1367
+ /**
1368
+ * Registers a callback function that wraps around all tests within the current suite.
1369
+ * The callback receives a `runSuite` function that must be called to run the suite's tests.
1370
+ * This hook is useful for scenarios where you need to wrap an entire suite in a context
1371
+ * (e.g., starting a server, opening a database connection that all tests share).
1372
+ *
1373
+ * **Note:** When multiple `aroundAll` hooks are registered, they are nested inside each other.
1374
+ * The first registered hook is the outermost wrapper.
1375
+ *
1376
+ * @param {Function} fn - The callback function that wraps the suite. Must call `runSuite()` to run the tests.
1377
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1378
+ * @returns {void}
1379
+ * @example
1380
+ * ```ts
1381
+ * // Example of using aroundAll to wrap suite in a tracing span
1382
+ * aroundAll(async (runSuite) => {
1383
+ * await tracer.trace('test-suite', runSuite);
1384
+ * });
1385
+ * ```
1386
+ * @example
1387
+ * ```ts
1388
+ * // Example of using aroundAll with fixtures
1389
+ * aroundAll(async (runSuite, { db }) => {
1390
+ * await db.transaction(() => runSuite());
1391
+ * });
1392
+ * ```
1393
+ */
1394
+ declare function aroundAll<ExtraContext = object>(this: unknown, fn: AroundAllListener<ExtraContext>, timeout?: number): void;
1395
+ /**
1396
+ * Registers a callback function that wraps around each test within the current suite.
1397
+ * The callback receives a `runTest` function that must be called to run the test.
1398
+ * This hook is useful for scenarios where you need to wrap tests in a context (e.g., database transactions).
1399
+ *
1400
+ * **Note:** When multiple `aroundEach` hooks are registered, they are nested inside each other.
1401
+ * The first registered hook is the outermost wrapper.
1402
+ *
1403
+ * @param {Function} fn - The callback function that wraps the test. Must call `runTest()` to run the test.
1404
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1405
+ * @returns {void}
1406
+ * @example
1407
+ * ```ts
1408
+ * // Example of using aroundEach to wrap tests in a database transaction
1409
+ * aroundEach(async (runTest) => {
1410
+ * await database.transaction(() => runTest());
1411
+ * });
1412
+ * ```
1413
+ * @example
1414
+ * ```ts
1415
+ * // Example of using aroundEach with fixtures
1416
+ * aroundEach(async (runTest, { db }) => {
1417
+ * await db.transaction(() => runTest());
1418
+ * });
1419
+ * ```
1420
+ */
1421
+ declare function aroundEach<ExtraContext = object>(fn: AroundEachListener<ExtraContext>, timeout?: number): void;
1422
+
1423
+ type ChainableFunction<
1424
+ T extends string,
1425
+ F extends (...args: any) => any,
1426
+ C = object
1427
+ > = F & { [x in T] : ChainableFunction<T, F, C> } & {
1428
+ fn: (this: Record<T, any>, ...args: Parameters<F>) => ReturnType<F>;
1429
+ } & C;
1430
+ type TypedChainableFunction<
1431
+ T,
1432
+ F extends (...args: any) => any,
1433
+ C = object
1434
+ > = F & { [x in keyof T] : TypedChainableFunction<T, F, C> } & {
1435
+ fn: (this: Record<keyof T, any>, ...args: Parameters<F>) => ReturnType<F>;
1436
+ } & C;
1437
+ declare function createChainable<
1438
+ T extends string,
1439
+ Args extends any[],
1440
+ R = any
1441
+ >(keys: T[], fn: (this: Record<T, any>, ...args: Args) => R, context?: Record<string, any>): ChainableFunction<T, (...args: Args) => R>;
1442
+
1443
+ type RunMode = "run" | "skip" | "only" | "todo" | "queued";
1444
+ type TaskState = RunMode | "pass" | "fail";
1445
+ interface TaskBase {
1446
+ /**
1447
+ * Unique task identifier. Based on the file id and the position of the task.
1448
+ * The id of the file task is based on the file path relative to root and project name.
1449
+ * It will not change between runs.
1450
+ * @example `1201091390`, `1201091390_0`, `1201091390_0_1`
1451
+ */
1452
+ id: string;
1453
+ /**
1454
+ * Task name provided by the user. If no name was provided, it will be an empty string.
1455
+ */
1456
+ name: string;
1457
+ /**
1458
+ * Full name including the file path, any parent suites, and this task's name.
1459
+ *
1460
+ * Uses ` > ` as the separator between levels.
1461
+ *
1462
+ * @example
1463
+ * // file
1464
+ * 'test/task-names.test.ts'
1465
+ * @example
1466
+ * // suite
1467
+ * 'test/task-names.test.ts > meal planning'
1468
+ * 'test/task-names.test.ts > meal planning > grocery lists'
1469
+ * @example
1470
+ * // test
1471
+ * 'test/task-names.test.ts > meal planning > grocery lists > calculates ingredients'
1472
+ */
1473
+ fullName: string;
1474
+ /**
1475
+ * Full name excluding the file path, including any parent suites and this task's name. `undefined` for file tasks.
1476
+ *
1477
+ * Uses ` > ` as the separator between levels.
1478
+ *
1479
+ * @example
1480
+ * // file
1481
+ * undefined
1482
+ * @example
1483
+ * // suite
1484
+ * 'meal planning'
1485
+ * 'meal planning > grocery lists'
1486
+ * @example
1487
+ * // test
1488
+ * 'meal planning > grocery lists > calculates ingredients'
1489
+ */
1490
+ fullTestName?: string;
1491
+ /**
1492
+ * Task mode.
1493
+ * - **skip**: task is skipped
1494
+ * - **only**: only this task and other tasks with `only` mode will run
1495
+ * - **todo**: task is marked as a todo, alias for `skip`
1496
+ * - **run**: task will run or already ran
1497
+ * - **queued**: task will start running next. It can only exist on the File
1498
+ */
1499
+ mode: RunMode;
1500
+ /**
1501
+ * Custom metadata for the task. JSON reporter will save this data.
1502
+ */
1503
+ meta: TaskMeta;
1504
+ /**
1505
+ * Whether the task was produced with `.each()` method.
1506
+ */
1507
+ each?: boolean;
1508
+ /**
1509
+ * Whether the task should run concurrently with other tasks.
1510
+ */
1511
+ concurrent?: boolean;
1512
+ /**
1513
+ * Whether the tasks of the suite run in a random order.
1514
+ */
1515
+ shuffle?: boolean;
1516
+ /**
1517
+ * Suite that this task is part of. File task or the global suite will have no parent.
1518
+ */
1519
+ suite?: Suite;
1520
+ /**
1521
+ * Result of the task. Suite and file tasks will only have the result if there
1522
+ * was an error during collection or inside `afterAll`/`beforeAll`.
1523
+ */
1524
+ result?: TaskResult;
1525
+ /**
1526
+ * Retry configuration for the task.
1527
+ * - If a number, specifies how many times to retry
1528
+ * - If an object, allows fine-grained retry control
1529
+ * @default 0
1530
+ */
1531
+ retry?: Retry;
1532
+ /**
1533
+ * The amount of times the task should be repeated after the successful run.
1534
+ * If the task fails, it will not be retried unless `retry` is specified.
1535
+ * @default 0
1536
+ */
1537
+ repeats?: number;
1538
+ /**
1539
+ * Location of the task in the file. This field is populated only if
1540
+ * `includeTaskLocation` option is set. It is generated by calling `new Error`
1541
+ * and parsing the stack trace, so the location might differ depending on the runtime.
1542
+ */
1543
+ location?: Location;
1544
+ /**
1545
+ * If the test was collected by parsing the file AST, and the name
1546
+ * is not a static string, this property will be set to `true`.
1547
+ * @experimental
1548
+ */
1549
+ dynamic?: boolean;
1550
+ /**
1551
+ * Custom tags of the task. Useful for filtering tasks.
1552
+ */
1553
+ tags?: string[];
1554
+ logs?: UserConsoleLog[];
1555
+ }
1556
+ interface TaskPopulated extends TaskBase {
1557
+ /**
1558
+ * File task. It's the root task of the file.
1559
+ */
1560
+ file: File;
1561
+ /**
1562
+ * Whether the task should succeed if it fails. If the task fails, it will be marked as passed.
1563
+ */
1564
+ fails?: boolean;
1565
+ /**
1566
+ * Store promises (from async expects) to wait for them before finishing the test
1567
+ */
1568
+ promises?: Promise<any>[];
1569
+ }
1570
+ /**
1571
+ * Custom metadata that can be used in reporters.
1572
+ */
1573
+ interface TaskMeta {
1574
+ typecheck?: boolean;
1575
+ benchmark?: boolean;
1576
+ __vitest_label__?: string;
1577
+ }
1578
+ /**
1579
+ * The result of calling a task.
1580
+ */
1581
+ interface TaskResult {
1582
+ /**
1583
+ * State of the task. Inherits the `task.mode` during collection.
1584
+ * When the task has finished, it will be changed to `pass` or `fail`.
1585
+ * - **pass**: task ran successfully
1586
+ * - **fail**: task failed
1587
+ */
1588
+ state: TaskState;
1589
+ /**
1590
+ * Errors that occurred during the task execution. It is possible to have several errors
1591
+ * if `expect.soft()` failed multiple times or `retry` was triggered.
1592
+ */
1593
+ errors?: TestError[];
1594
+ /**
1595
+ * How long in milliseconds the task took to run.
1596
+ */
1597
+ duration?: number;
1598
+ /**
1599
+ * Time in milliseconds when the task started running.
1600
+ */
1601
+ startTime?: number;
1602
+ /**
1603
+ * Heap size in bytes after the task finished.
1604
+ * Only available if `logHeapUsage` option is set and `process.memoryUsage` is defined.
1605
+ */
1606
+ heap?: number;
1607
+ /**
1608
+ * State of related to this task hooks. Useful during reporting.
1609
+ */
1610
+ hooks?: Partial<Record<keyof SuiteHooks, TaskState>>;
1611
+ /**
1612
+ * The amount of times the task was retried. The task is retried only if it
1613
+ * failed and `retry` option is set.
1614
+ */
1615
+ retryCount?: number;
1616
+ /**
1617
+ * The amount of times the task was repeated. The task is repeated only if
1618
+ * `repeats` option is set. This number also contains `retryCount`.
1619
+ */
1620
+ repeatCount?: number;
1621
+ }
1622
+ /** The time spent importing & executing a non-externalized file. */
1623
+ interface ImportDuration {
1624
+ /** The time spent importing & executing the file itself, not counting all non-externalized imports that the file does. */
1625
+ selfTime: number;
1626
+ /** The time spent importing & executing the file and all its imports. */
1627
+ totalTime: number;
1628
+ /** Will be set to `true`, if the module was externalized. In this case totalTime and selfTime are identical. */
1629
+ external?: boolean;
1630
+ /** Which module imported this module first. All subsequent imports are cached. */
1631
+ importer?: string;
1632
+ }
1633
+ /**
1634
+ * The tuple representing a single task update.
1635
+ * Usually reported after the task finishes.
1636
+ */
1637
+ type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta];
1638
+ interface TaskEventData {
1639
+ annotation?: TestAnnotation | undefined;
1640
+ artifact?: TestArtifact | undefined;
1641
+ }
1642
+ type TaskEventPack = [id: string, event: TaskUpdateEvent, data: TaskEventData | undefined];
1643
+ type TaskUpdateEvent = "test-failed-early" | "suite-failed-early" | "test-prepare" | "test-finished" | "test-retried" | "test-cancel" | "suite-prepare" | "suite-finished" | "before-hook-start" | "before-hook-end" | "after-hook-start" | "after-hook-end" | "test-annotation" | "test-artifact";
1644
+ interface Suite extends TaskBase {
1645
+ type: "suite";
1646
+ /**
1647
+ * File task. It's the root task of the file.
1648
+ */
1649
+ file: File;
1650
+ /**
1651
+ * An array of tasks that are part of the suite.
1652
+ */
1653
+ tasks: Task[];
1654
+ }
1655
+ interface File extends Suite {
1656
+ /**
1657
+ * The name of the pool that the file belongs to.
1658
+ * @default 'forks'
1659
+ */
1660
+ pool?: string;
1661
+ /**
1662
+ * The environment that processes the file on the server.
1663
+ */
1664
+ viteEnvironment?: string;
1665
+ /**
1666
+ * The path to the file in UNIX format.
1667
+ */
1668
+ filepath: string;
1669
+ /**
1670
+ * The name of the workspace project the file belongs to.
1671
+ */
1672
+ projectName: string | undefined;
1673
+ /**
1674
+ * The time it took to collect all tests in the file.
1675
+ * This time also includes importing all the file dependencies.
1676
+ */
1677
+ collectDuration?: number;
1678
+ /**
1679
+ * The time it took to import the setup file.
1680
+ */
1681
+ setupDuration?: number;
1682
+ /** The time spent importing every non-externalized dependency that Vitest has processed. */
1683
+ importDurations?: Record<string, ImportDuration>;
1684
+ prepareDuration?: number;
1685
+ environmentLoad?: number;
1686
+ concurrencyId: number;
1687
+ workerId: number;
1688
+ }
1689
+ interface Test<ExtraContext = object> extends TaskPopulated {
1690
+ type: "test";
1691
+ /**
1692
+ * Test context that will be passed to the test function.
1693
+ */
1694
+ context: TestContext & ExtraContext;
1695
+ /**
1696
+ * The test timeout in milliseconds.
1697
+ */
1698
+ timeout: number;
1699
+ /**
1700
+ * An array of custom annotations.
1701
+ */
1702
+ annotations: TestAnnotation[];
1703
+ /**
1704
+ * An array of artifacts produced by the test.
1705
+ *
1706
+ * @experimental
1707
+ */
1708
+ artifacts: TestArtifact[];
1709
+ fullTestName: string;
1710
+ /**
1711
+ * An array of benchmark results generated by `context.bench` function.
1712
+ * The benchmark is added only after `bench().run` or `bench.compare` is resolved.
1713
+ *
1714
+ * @experimental
1715
+ */
1716
+ benchmarks: TestBenchmark[];
1717
+ }
1718
+ interface TestBenchmark {
1719
+ name: string;
1720
+ tasks: TestBenchmarkTask[];
1721
+ }
1722
+ type TestBenchmarkStatistics = Statistics;
1723
+ interface BaselineData {
1724
+ latency: TestBenchmarkStatistics;
1725
+ throughput: TestBenchmarkStatistics;
1726
+ period: number;
1727
+ totalTime: number;
1728
+ }
1729
+ interface TestBenchmarkTask {
1730
+ name: string;
1731
+ latency: TestBenchmarkStatistics;
1732
+ throughput: TestBenchmarkStatistics;
1733
+ period: number;
1734
+ totalTime: number;
1735
+ rank: number;
1736
+ perProject?: boolean;
1737
+ /**
1738
+ * `true` when the task was produced by `bench.from()` rather than by
1739
+ * executing a function. Reporters can use this to render the row as a
1740
+ * static reference (no margin of error, no samples).
1741
+ */
1742
+ fromStore?: boolean;
1743
+ }
1744
+ type Task = Test | Suite | File;
1745
+ type TestFunction<ExtraContext = object> = (context: TestContext & ExtraContext) => Awaitable<any> | void;
1746
+ type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
1747
+ 1: [T[0]];
1748
+ 2: [T[0], T[1]];
1749
+ 3: [T[0], T[1], T[2]];
1750
+ 4: [T[0], T[1], T[2], T[3]];
1751
+ 5: [T[0], T[1], T[2], T[3], T[4]];
1752
+ 6: [T[0], T[1], T[2], T[3], T[4], T[5]];
1753
+ 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]];
1754
+ 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]];
1755
+ 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]];
1756
+ 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]];
1757
+ fallback: Array<T extends ReadonlyArray<infer U> ? U : any>;
1758
+ }[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : "fallback"];
1759
+ interface EachFunctionReturn<T extends any[]> {
1760
+ (name: string | Function, fn: (...args: T) => Awaitable<void>, options?: number): void;
1761
+ (name: string | Function, options: TestCollectorOptions, fn: (...args: T) => Awaitable<void>): void;
1762
+ }
1763
+ interface TestEachFunction {
1764
+ <T extends any[] | [any]>(cases: ReadonlyArray<T>): EachFunctionReturn<T>;
1765
+ <T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): EachFunctionReturn<ExtractEachCallbackArgs<T>>;
1766
+ <T>(cases: ReadonlyArray<T>): EachFunctionReturn<T[]>;
1767
+ (...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
1768
+ }
1769
+ interface TestForFunctionReturn<
1770
+ Arg,
1771
+ Context
1772
+ > {
1773
+ (name: string | Function, fn: (arg: Arg, context: Context) => Awaitable<void>): void;
1774
+ (name: string | Function, options: TestCollectorOptions, fn: (args: Arg, context: Context) => Awaitable<void>): void;
1775
+ }
1776
+ interface TestForFunction<ExtraContext> {
1777
+ <T>(cases: ReadonlyArray<T>): TestForFunctionReturn<T, TestContext & ExtraContext>;
1778
+ (strings: TemplateStringsArray, ...values: any[]): TestForFunctionReturn<any, TestContext & ExtraContext>;
1779
+ }
1780
+ interface SuiteForFunction {
1781
+ <T>(cases: ReadonlyArray<T>): EachFunctionReturn<[T]>;
1782
+ (...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
1783
+ }
1784
+ interface TestCollectorCallable<C = object> {
1785
+ <ExtraContext extends C>(name: string | Function, fn?: TestFunction<ExtraContext>, options?: number): void;
1786
+ <ExtraContext extends C>(name: string | Function, options?: TestCollectorOptions, fn?: TestFunction<ExtraContext>): void;
1787
+ }
1788
+ type ChainableTestContextMap = Pick<Required<TestOptions>, "concurrent" | "only" | "skip" | "todo" | "fails">;
1789
+ type ChainableTestAPI<ExtraContext = object> = TypedChainableFunction<ChainableTestContextMap, TestCollectorCallable<ExtraContext>, {
1790
+ each: TestEachFunction;
1791
+ for: TestForFunction<ExtraContext>;
1792
+ }>;
1793
+ type TestCollectorOptions = Omit<TestOptions, "shuffle">;
1794
+ /**
1795
+ * Retry configuration for tests.
1796
+ * Can be a number for simple retry count, or an object for advanced retry control.
1797
+ */
1798
+ type Retry = number | {
1799
+ /**
1800
+ * The number of times to retry the test if it fails.
1801
+ * @default 0
1802
+ */
1803
+ count?: number;
1804
+ /**
1805
+ * Delay in milliseconds between retry attempts.
1806
+ * @default 0
1807
+ */
1808
+ delay?: number;
1809
+ /**
1810
+ * Condition to determine if a test should be retried based on the error.
1811
+ * - If a RegExp, it is tested against the error message
1812
+ * - If a function, called with the TestError object; return true to retry
1813
+ *
1814
+ * NOTE: Functions can only be used in test files, not in vitest.config.ts,
1815
+ * because the configuration is serialized when passed to worker threads.
1816
+ *
1817
+ * @default undefined (retry on all errors)
1818
+ */
1819
+ condition?: RegExp | ((error: TestError) => boolean);
1820
+ };
1821
+ /**
1822
+ * Serializable retry configuration (used in config files).
1823
+ * Functions cannot be serialized, so only string conditions are allowed.
1824
+ */
1825
+ type SerializableRetry = number | {
1826
+ /**
1827
+ * The number of times to retry the test if it fails.
1828
+ * @default 0
1829
+ */
1830
+ count?: number;
1831
+ /**
1832
+ * Delay in milliseconds between retry attempts.
1833
+ * @default 0
1834
+ */
1835
+ delay?: number;
1836
+ /**
1837
+ * Condition to determine if a test should be retried based on the error.
1838
+ * Must be a RegExp tested against the error message.
1839
+ *
1840
+ * @default undefined (retry on all errors)
1841
+ */
1842
+ condition?: RegExp;
1843
+ };
1844
+ interface TestOptions {
1845
+ /**
1846
+ * Test timeout.
1847
+ */
1848
+ timeout?: number;
1849
+ /**
1850
+ * Retry configuration for the test.
1851
+ * - If a number, specifies how many times to retry
1852
+ * - If an object, allows fine-grained retry control
1853
+ * @default 0
1854
+ */
1855
+ retry?: Retry;
1856
+ /**
1857
+ * How many times the test will run again.
1858
+ * Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default.
1859
+ *
1860
+ * @default 0
1861
+ */
1862
+ repeats?: number;
1863
+ /**
1864
+ * Whether suites and tests run concurrently.
1865
+ * Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`.
1866
+ */
1867
+ concurrent?: boolean;
1868
+ /**
1869
+ * Whether the test should be skipped.
1870
+ */
1871
+ skip?: boolean;
1872
+ /**
1873
+ * Should this test be the only one running in a suite.
1874
+ */
1875
+ only?: boolean;
1876
+ /**
1877
+ * Whether the test should be skipped and marked as a todo.
1878
+ */
1879
+ todo?: boolean;
1880
+ /**
1881
+ * Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail.
1882
+ */
1883
+ fails?: boolean;
1884
+ /**
1885
+ * Custom tags of the test. Useful for filtering tests.
1886
+ */
1887
+ tags?: keyof TestTags extends never ? string[] | string : TestTags[keyof TestTags] | TestTags[keyof TestTags][];
1888
+ /**
1889
+ * Custom test metadata available to reporters.
1890
+ */
1891
+ meta?: Partial<TaskMeta>;
1892
+ }
1893
+ interface TestTags {}
1894
+ interface TestTagDefinition extends Omit<TestOptions, "tags" | "shuffle"> {
1895
+ /**
1896
+ * The name of the tag. This is what you use in the `tags` array in tests.
1897
+ */
1898
+ name: keyof TestTags extends never ? string : TestTags[keyof TestTags];
1899
+ /**
1900
+ * A description for the tag. This will be shown in the CLI help and UI.
1901
+ */
1902
+ description?: string;
1903
+ /**
1904
+ * Priority for merging options when multiple tags with the same options are applied to a test.
1905
+ *
1906
+ * Lower number means higher priority. E.g., priority 1 takes precedence over priority 3.
1907
+ */
1908
+ priority?: number;
1909
+ }
1910
+ interface SuiteOptions extends TestOptions {
1911
+ /**
1912
+ * Whether the tasks of the suite run in a random order.
1913
+ */
1914
+ shuffle?: boolean;
1915
+ }
1916
+ interface ExtendedAPI<ExtraContext> {
1917
+ skipIf: (condition: any) => ChainableTestAPI<ExtraContext>;
1918
+ runIf: (condition: any) => ChainableTestAPI<ExtraContext>;
1919
+ }
1920
+ interface Hooks<ExtraContext> {
1921
+ /**
1922
+ * Suite-level hooks only receive file/worker scoped fixtures.
1923
+ * Test-scoped fixtures are NOT available in beforeAll/afterAll/aroundAll.
1924
+ */
1925
+ beforeAll: typeof beforeAll<ExtractSuiteContext<ExtraContext>>;
1926
+ afterAll: typeof afterAll<ExtractSuiteContext<ExtraContext>>;
1927
+ aroundAll: typeof aroundAll<ExtractSuiteContext<ExtraContext>>;
1928
+ /**
1929
+ * Test-level hooks receive all fixtures including test-scoped ones.
1930
+ */
1931
+ beforeEach: typeof beforeEach<ExtraContext>;
1932
+ afterEach: typeof afterEach<ExtraContext>;
1933
+ aroundEach: typeof aroundEach<ExtraContext>;
1934
+ }
1935
+ type TestAPI<ExtraContext = object> = ChainableTestAPI<ExtraContext> & ExtendedAPI<ExtraContext> & Hooks<ExtraContext> & {
1936
+ /**
1937
+ * Extend the test API with custom fixtures.
1938
+ *
1939
+ * @example
1940
+ * ```ts
1941
+ * // Simple test fixtures (backward compatible)
1942
+ * const myTest = test.extend<{ foo: string }>({
1943
+ * foo: 'value',
1944
+ * })
1945
+ *
1946
+ * // With scoped fixtures - use $test/$file/$worker structure
1947
+ * const myTest = test.extend<{
1948
+ * $test: { testData: string }
1949
+ * $file: { fileDb: Database }
1950
+ * $worker: { workerConfig: Config }
1951
+ * }>({
1952
+ * testData: async ({ fileDb }, use) => {
1953
+ * await use(await fileDb.getData())
1954
+ * },
1955
+ * fileDb: [async ({ workerConfig }, use) => {
1956
+ * // File fixture can only access workerConfig, NOT testData
1957
+ * const db = new Database(workerConfig)
1958
+ * await use(db)
1959
+ * await db.close()
1960
+ * }, { scope: 'file' }],
1961
+ * workerConfig: [async ({}, use) => {
1962
+ * // Worker fixture can only access other worker fixtures
1963
+ * await use(loadConfig())
1964
+ * }, { scope: 'worker' }],
1965
+ * })
1966
+ *
1967
+ * // Builder pattern with automatic type inference
1968
+ * const myTest = test
1969
+ * .extend('config', { scope: 'worker' }, async ({}) => {
1970
+ * return { port: 3000 } // Type inferred as { port: number }
1971
+ * })
1972
+ * .extend('db', { scope: 'file' }, async ({ config }, { onCleanup }) => {
1973
+ * // TypeScript knows config is { port: number }
1974
+ * const db = new Database(config.port)
1975
+ * onCleanup(() => db.close()) // Register cleanup
1976
+ * return db // Type inferred as Database
1977
+ * })
1978
+ * .extend('data', async ({ db }) => {
1979
+ * // TypeScript knows db is Database
1980
+ * return await db.getData() // Type inferred from return
1981
+ * })
1982
+ * ```
1983
+ */
1984
+ extend: {
1985
+ <
1986
+ K extends string,
1987
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
1988
+ >(name: K, options: WorkerScopeFixtureOptions, fn: BuilderFixtureFn<T, WorkerScopeContext<ExtraContext>>): TestAPI<AddBuilderWorker<ExtraContext, K, T>>;
1989
+ <
1990
+ K extends string,
1991
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
1992
+ >(name: K, options: FileScopeFixtureOptions, fn: BuilderFixtureFn<T, FileScopeContext<ExtraContext>>): TestAPI<AddBuilderFile<ExtraContext, K, T>>;
1993
+ <
1994
+ K extends string,
1995
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
1996
+ >(name: K, options: TestScopeFixtureOptions, fn: BuilderFixtureFn<T, TestScopeContext<ExtraContext>>): TestAPI<AddBuilderTest<ExtraContext, K, T>>;
1997
+ <
1998
+ K extends string,
1999
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2000
+ >(name: K, fn: BuilderFixtureFn<T, TestScopeContext<ExtraContext>>): TestAPI<AddBuilderTest<ExtraContext, K, T>>;
2001
+ <
2002
+ K extends string,
2003
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2004
+ >(name: K, options: WorkerScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI<AddBuilderWorker<ExtraContext, K, T>>;
2005
+ <
2006
+ K extends string,
2007
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2008
+ >(name: K, options: FileScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI<AddBuilderFile<ExtraContext, K, T>>;
2009
+ <
2010
+ K extends string,
2011
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2012
+ >(name: K, options: TestScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI<AddBuilderTest<ExtraContext, K, T>>;
2013
+ <
2014
+ K extends string,
2015
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2016
+ >(name: K, value: T extends (...args: any[]) => any ? never : T): TestAPI<AddBuilderTest<ExtraContext, K, T>>;
2017
+ <T extends ScopedFixturesDef>(fixtures: ScopedFixturesObject<T, ExtraContext>): TestAPI<ExtractScopedFixtures<T> & ExtraContext>;
2018
+ <T extends Record<string, any> = object>(fixtures: Fixtures<T, ExtraContext>): TestAPI<{ [K in keyof T | keyof ExtraContext] : K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never }>;
2019
+ };
2020
+ /**
2021
+ * Overwrite fixture values for the current suite scope.
2022
+ * Supports both object syntax and builder pattern.
2023
+ *
2024
+ * @example
2025
+ * ```ts
2026
+ * describe('with custom config', () => {
2027
+ * // Object syntax
2028
+ * test.override({ config: { port: 4000 } })
2029
+ *
2030
+ * // Builder pattern - value
2031
+ * test.override('config', { port: 4000 })
2032
+ *
2033
+ * // Builder pattern - function
2034
+ * test.override('config', () => ({ port: 4000 }))
2035
+ *
2036
+ * // Builder pattern - function with cleanup
2037
+ * test.override('db', async ({ config }, { onCleanup }) => {
2038
+ * const db = await createDb(config)
2039
+ * onCleanup(() => db.close())
2040
+ * return db
2041
+ * })
2042
+ * })
2043
+ * ```
2044
+ */
2045
+ override: {
2046
+ <K extends keyof ExtraContext>(name: K, options: FixtureOptions, fn: BuilderFixtureFn<ExtraContext[K], ExtraContext & TestContext>): TestAPI<ExtraContext>;
2047
+ <K extends keyof ExtraContext>(name: K, fn: BuilderFixtureFn<ExtraContext[K], ExtraContext & TestContext>): TestAPI<ExtraContext>;
2048
+ <K extends keyof ExtraContext>(name: K, options: FixtureOptions, value: ExtraContext[K] extends (...args: any[]) => any ? never : ExtraContext[K]): TestAPI<ExtraContext>;
2049
+ <K extends keyof ExtraContext>(name: K, value: ExtraContext[K] extends (...args: any[]) => any ? never : ExtraContext[K]): TestAPI<ExtraContext>;
2050
+ (fixtures: Partial<Fixtures<ExtraContext>>): TestAPI<ExtraContext>;
2051
+ };
2052
+ /**
2053
+ * @deprecated Use `test.override()` instead
2054
+ */
2055
+ scoped: (fixtures: Partial<Fixtures<ExtraContext>>) => TestAPI<ExtraContext>;
2056
+ describe: SuiteAPI<ExtraContext>;
2057
+ suite: SuiteAPI<ExtraContext>;
2058
+ };
2059
+ interface FixtureOptions {
2060
+ /**
2061
+ * Whether to automatically set up current fixture, even though it's not being used.
2062
+ * Test-scoped auto fixtures are not initialized in suite-level hooks (`beforeAll`/`afterAll`/`aroundAll`).
2063
+ * @default false
2064
+ */
2065
+ auto?: boolean;
2066
+ /**
2067
+ * Indicated if the injected value from the config should be preferred over the fixture value
2068
+ */
2069
+ injected?: boolean;
2070
+ /**
2071
+ * When should the fixture be set up.
2072
+ * - **test**: fixture will be set up before every test
2073
+ * - **worker**: fixture will be set up once per worker
2074
+ * - **file**: fixture will be set up once per file
2075
+ *
2076
+ * **Warning:** The `vmThreads` and `vmForks` pools initiate worker fixtures once per test file.
2077
+ * @default 'test'
2078
+ */
2079
+ scope?: "test" | "worker" | "file";
2080
+ }
2081
+ /**
2082
+ * Options for test-scoped fixtures.
2083
+ * Test fixtures are set up before each test and have access to all fixtures.
2084
+ */
2085
+ interface TestScopeFixtureOptions extends Omit<FixtureOptions, "scope"> {
2086
+ /**
2087
+ * @default 'test'
2088
+ */
2089
+ scope?: "test";
2090
+ }
2091
+ /**
2092
+ * Options for file-scoped fixtures.
2093
+ * File fixtures are set up once per file and can only access other file fixtures and worker fixtures.
2094
+ */
2095
+ interface FileScopeFixtureOptions extends Omit<FixtureOptions, "scope"> {
2096
+ /**
2097
+ * Must be 'file' for file-scoped fixtures.
2098
+ */
2099
+ scope: "file";
2100
+ }
2101
+ /**
2102
+ * Options for worker-scoped fixtures.
2103
+ * Worker fixtures are set up once per worker and can only access other worker fixtures.
2104
+ */
2105
+ interface WorkerScopeFixtureOptions extends Omit<FixtureOptions, "scope"> {
2106
+ /**
2107
+ * Must be 'worker' for worker-scoped fixtures.
2108
+ */
2109
+ scope: "worker";
2110
+ }
2111
+ type Use<T> = (value: T) => Promise<void>;
2112
+ /**
2113
+ * Cleanup registration function for builder pattern fixtures.
2114
+ * Call this to register a cleanup function that runs after the test/file/worker completes.
2115
+ *
2116
+ * **Note:** This function can only be called once per fixture. If you need multiple
2117
+ * cleanup operations, either combine them into a single cleanup function or split
2118
+ * your fixture into multiple smaller fixtures.
2119
+ */
2120
+ type OnCleanup = (cleanup: () => Awaitable<void>) => void;
2121
+ /**
2122
+ * Builder pattern fixture function with automatic type inference.
2123
+ * Returns the fixture value directly (type is inferred from return).
2124
+ * Use onCleanup to register teardown logic.
2125
+ *
2126
+ * Parameters can be omitted if not needed:
2127
+ * - `async () => value` - no dependencies, no cleanup
2128
+ * - `async ({ dep }) => value` - with dependencies, no cleanup
2129
+ * - `async ({ dep }, { onCleanup }) => value` - with dependencies and cleanup
2130
+ */
2131
+ type BuilderFixtureFn<
2132
+ T,
2133
+ Context
2134
+ > = (context: Context, fixture: {
2135
+ onCleanup: OnCleanup;
2136
+ }) => T | Promise<T>;
2137
+ type ExtractSuiteContext<C> = C extends {
2138
+ $__worker?: any;
2139
+ } | {
2140
+ $__file?: any;
2141
+ } | {
2142
+ $__test?: any;
2143
+ } ? ExtractBuilderWorker<C> & ExtractBuilderFile<C> : C;
2144
+ /**
2145
+ * Extracts worker-scoped fixtures from a context that includes scope info.
2146
+ */
2147
+ type ExtractBuilderWorker<C> = C extends {
2148
+ $__worker?: infer W;
2149
+ } ? W extends Record<string, any> ? W : object : object;
2150
+ /**
2151
+ * Extracts file-scoped fixtures from a context that includes scope info.
2152
+ */
2153
+ type ExtractBuilderFile<C> = C extends {
2154
+ $__file?: infer F;
2155
+ } ? F extends Record<string, any> ? F : object : object;
2156
+ /**
2157
+ * Extracts test-scoped fixtures from a context that includes scope info.
2158
+ */
2159
+ type ExtractBuilderTest<C> = C extends {
2160
+ $__test?: infer T;
2161
+ } ? T extends Record<string, any> ? T : object : object;
2162
+ /**
2163
+ * Adds a worker fixture to the context with proper scope tracking.
2164
+ */
2165
+ type AddBuilderWorker<
2166
+ C,
2167
+ K extends string,
2168
+ V
2169
+ > = Omit<C, "$__worker"> & Record<K, V> & {
2170
+ readonly $__worker?: ExtractBuilderWorker<C> & Record<K, V>;
2171
+ readonly $__file?: ExtractBuilderFile<C>;
2172
+ readonly $__test?: ExtractBuilderTest<C>;
2173
+ };
2174
+ /**
2175
+ * Adds a file fixture to the context with proper scope tracking.
2176
+ */
2177
+ type AddBuilderFile<
2178
+ C,
2179
+ K extends string,
2180
+ V
2181
+ > = Omit<C, "$__file"> & Record<K, V> & {
2182
+ readonly $__worker?: ExtractBuilderWorker<C>;
2183
+ readonly $__file?: ExtractBuilderFile<C> & Record<K, V>;
2184
+ readonly $__test?: ExtractBuilderTest<C>;
2185
+ };
2186
+ /**
2187
+ * Adds a test fixture to the context with proper scope tracking.
2188
+ */
2189
+ type AddBuilderTest<
2190
+ C,
2191
+ K extends string,
2192
+ V
2193
+ > = Omit<C, "$__test"> & Record<K, V> & {
2194
+ readonly $__worker?: ExtractBuilderWorker<C>;
2195
+ readonly $__file?: ExtractBuilderFile<C>;
2196
+ readonly $__test?: ExtractBuilderTest<C> & Record<K, V>;
2197
+ };
2198
+ /**
2199
+ * Context available to worker-scoped fixtures.
2200
+ * Worker fixtures can only access other worker fixtures.
2201
+ * They do NOT have access to test context (task, expect, onTestFailed, etc.)
2202
+ * since they run once per worker, outside of any specific test.
2203
+ */
2204
+ type WorkerScopeContext<C> = ExtractBuilderWorker<C>;
2205
+ /**
2206
+ * Context available to file-scoped fixtures.
2207
+ * File fixtures can access worker and other file fixtures.
2208
+ * They do NOT have access to test context (task, expect, onTestFailed, etc.)
2209
+ * since they run once per file, outside of any specific test.
2210
+ */
2211
+ type FileScopeContext<C> = ExtractBuilderWorker<C> & ExtractBuilderFile<C>;
2212
+ /**
2213
+ * Context available to test-scoped fixtures (all fixtures + test context).
2214
+ */
2215
+ type TestScopeContext<C> = C & TestContext;
2216
+ type FixtureFn<
2217
+ T,
2218
+ K extends keyof T,
2219
+ ExtraContext
2220
+ > = (context: Omit<T, K> & ExtraContext, use: Use<T[K]>) => Promise<void>;
2221
+ type Fixture<
2222
+ T,
2223
+ K extends keyof T,
2224
+ ExtraContext = object
2225
+ > = ((...args: any) => any) extends T[K] ? T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never : T[K] | (T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never);
2226
+ /**
2227
+ * Fixture function with explicit context type for scoped fixtures.
2228
+ */
2229
+ type ScopedFixtureFn<
2230
+ Value,
2231
+ Context
2232
+ > = (context: Context, use: Use<Value>) => Promise<void>;
2233
+ /**
2234
+ * Fixtures definition for backward compatibility.
2235
+ * All fixtures are in T and any scope is allowed.
2236
+ */
2237
+ type Fixtures<
2238
+ T,
2239
+ ExtraContext = object
2240
+ > = { [K in keyof T] : Fixture<T, K, ExtraContext & TestContext> | [Fixture<T, K, ExtraContext & TestContext>, FixtureOptions?] };
2241
+ /**
2242
+ * Scoped fixtures definition using a single generic with optional scope keys.
2243
+ * This provides better ergonomics than multiple generics.
2244
+ * Uses $ prefix to avoid conflicts with fixture names.
2245
+ *
2246
+ * @example
2247
+ * ```ts
2248
+ * test.extend<{
2249
+ * $worker?: { config: Config }
2250
+ * $file?: { db: Database }
2251
+ * $test?: { data: string }
2252
+ * }>({ ... })
2253
+ * ```
2254
+ */
2255
+ interface ScopedFixturesDef {
2256
+ $test?: Record<string, any>;
2257
+ $file?: Record<string, any>;
2258
+ $worker?: Record<string, any>;
2259
+ }
2260
+ /**
2261
+ * Extracts fixture types from a ScopedFixturesDef.
2262
+ * Handles optional properties by using Exclude to remove undefined.
2263
+ */
2264
+ type ExtractScopedFixtures<T extends ScopedFixturesDef> = ([Exclude<T["$test"], undefined>] extends [never] ? object : Exclude<T["$test"], undefined>) & ([Exclude<T["$file"], undefined>] extends [never] ? object : Exclude<T["$file"], undefined>) & ([Exclude<T["$worker"], undefined>] extends [never] ? object : Exclude<T["$worker"], undefined>);
2265
+ /**
2266
+ * Creates the fixtures object type for ScopedFixturesDef with proper scope validation.
2267
+ * - Test fixtures: can be defined as value, function, or tuple with optional scope
2268
+ * - File fixtures: MUST have { scope: 'file' }
2269
+ * - Worker fixtures: MUST have { scope: 'worker' }
2270
+ */
2271
+ type ScopedFixturesObject<
2272
+ T extends ScopedFixturesDef,
2273
+ ExtraContext = object
2274
+ > = { [K in keyof NonNullable<T["$test"]>] : NonNullable<T["$test"]>[K] | ScopedFixtureFn<NonNullable<T["$test"]>[K], ExtractScopedFixtures<T> & ExtraContext & TestContext> | [ScopedFixtureFn<NonNullable<T["$test"]>[K], ExtractScopedFixtures<T> & ExtraContext & TestContext>, TestScopeFixtureOptions?] } & { [K in keyof NonNullable<T["$file"]>] : [ScopedFixtureFn<NonNullable<T["$file"]>[K], (NonNullable<T["$file"]> & NonNullable<T["$worker"]>) & ExtraContext>, FileScopeFixtureOptions] } & { [K in keyof NonNullable<T["$worker"]>] : [ScopedFixtureFn<NonNullable<T["$worker"]>[K], NonNullable<T["$worker"]> & ExtraContext>, WorkerScopeFixtureOptions] };
2275
+ interface SuiteCollectorCallable<ExtraContext = object> {
2276
+ <OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, fn?: SuiteFactory<OverrideExtraContext>, options?: number): SuiteCollector<OverrideExtraContext>;
2277
+ <OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, options: SuiteOptions, fn?: SuiteFactory<OverrideExtraContext>): SuiteCollector<OverrideExtraContext>;
2278
+ }
2279
+ type ChainableSuiteContextMap = Pick<Required<SuiteOptions>, "concurrent" | "only" | "skip" | "todo" | "shuffle">;
2280
+ type ChainableSuiteAPI<ExtraContext = object> = TypedChainableFunction<ChainableSuiteContextMap, SuiteCollectorCallable<ExtraContext>, {
2281
+ each: TestEachFunction;
2282
+ for: SuiteForFunction;
2283
+ }>;
2284
+ type SuiteAPI<ExtraContext = object> = ChainableSuiteAPI<ExtraContext> & {
2285
+ skipIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
2286
+ runIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
2287
+ };
2288
+ interface BeforeAllListener<ExtraContext = object> {
2289
+ (context: ExtraContext, suite: Readonly<Suite | File>): Awaitable<unknown>;
2290
+ }
2291
+ interface AfterAllListener<ExtraContext = object> {
2292
+ (context: ExtraContext, suite: Readonly<Suite | File>): Awaitable<unknown>;
2293
+ }
2294
+ interface BeforeEachListener<ExtraContext = object> {
2295
+ (context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
2296
+ }
2297
+ interface AfterEachListener<ExtraContext = object> {
2298
+ (context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
2299
+ }
2300
+ interface AroundEachListener<ExtraContext = object> {
2301
+ (runTest: () => Promise<void>, context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
2302
+ }
2303
+ interface AroundAllListener<ExtraContext = object> {
2304
+ (runSuite: () => Promise<void>, context: ExtraContext, suite: Readonly<Suite | File>): Awaitable<unknown>;
2305
+ }
2306
+ interface RegisteredAllListener {
2307
+ (suite: Readonly<Suite | File>): Awaitable<unknown>;
2308
+ }
2309
+ interface RegisteredAroundAllListener {
2310
+ (runSuite: () => Promise<void>, suite: Readonly<Suite | File>): Awaitable<unknown>;
2311
+ }
2312
+ interface SuiteHooks<ExtraContext = object> {
2313
+ beforeAll: RegisteredAllListener[];
2314
+ afterAll: RegisteredAllListener[];
2315
+ aroundAll: RegisteredAroundAllListener[];
2316
+ beforeEach: BeforeEachListener<ExtraContext>[];
2317
+ afterEach: AfterEachListener<ExtraContext>[];
2318
+ aroundEach: AroundEachListener<ExtraContext>[];
2319
+ }
2320
+ interface TaskCustomOptions extends TestOptions {
2321
+ /**
2322
+ * Whether the task was produced with `.each()` method.
2323
+ */
2324
+ each?: boolean;
2325
+ /**
2326
+ * Task fixtures.
2327
+ */
2328
+ fixtures?: TestFixtures;
2329
+ /**
2330
+ * Function that will be called when the task is executed.
2331
+ * If nothing is provided, the runner will try to get the function using `getFn(task)`.
2332
+ * If the runner cannot find the function, the task will be marked as failed.
2333
+ */
2334
+ handler?: (context: TestContext) => Awaitable<void>;
2335
+ }
2336
+ interface SuiteCollector<ExtraContext = object> {
2337
+ readonly name: string;
2338
+ readonly mode: RunMode;
2339
+ options?: SuiteOptions;
2340
+ type: "collector";
2341
+ test: TestAPI<ExtraContext>;
2342
+ tasks: (Suite | Test<ExtraContext> | SuiteCollector<ExtraContext>)[];
2343
+ file: File;
2344
+ suite?: Suite;
2345
+ task: (name: string, options?: TaskCustomOptions) => Test<ExtraContext>;
2346
+ collect: (file: File) => Promise<Suite>;
2347
+ clear: () => void;
2348
+ on: <T extends keyof SuiteHooks<ExtraContext>>(name: T, ...fn: SuiteHooks<ExtraContext>[T]) => void;
2349
+ }
2350
+ type SuiteFactory<ExtraContext = object> = (test: TestAPI<ExtraContext>) => Awaitable<void>;
2351
+ /**
2352
+ * User's custom test context.
2353
+ */
2354
+ interface TestContext {
2355
+ /**
2356
+ * Metadata of the current test
2357
+ */
2358
+ readonly task: Readonly<Test>;
2359
+ /**
2360
+ * An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that will be aborted if the test times out or
2361
+ * the test run was cancelled.
2362
+ * @see {@link https://vitest.dev/guide/test-context#signal}
2363
+ */
2364
+ readonly signal: AbortSignal;
2365
+ /**
2366
+ * Register a callback to run when this specific test fails.
2367
+ * Useful when tests run concurrently.
2368
+ * @see {@link https://vitest.dev/guide/test-context#ontestfailed}
2369
+ */
2370
+ readonly onTestFailed: (fn: OnTestFailedHandler, timeout?: number) => void;
2371
+ /**
2372
+ * Register a callback to run when this specific test finishes.
2373
+ * Useful when tests run concurrently.
2374
+ * @see {@link https://vitest.dev/guide/test-context#ontestfinished}
2375
+ */
2376
+ readonly onTestFinished: (fn: OnTestFinishedHandler, timeout?: number) => void;
2377
+ /**
2378
+ * Mark tests as skipped. All execution after this call will be skipped.
2379
+ * This function throws an error, so make sure you are not catching it accidentally.
2380
+ * @see {@link https://vitest.dev/guide/test-context#skip}
2381
+ */
2382
+ readonly skip: {
2383
+ (note?: string): never;
2384
+ (condition: boolean, note?: string): void;
2385
+ };
2386
+ /**
2387
+ * Add a test annotation that will be displayed by your reporter.
2388
+ * @see {@link https://vitest.dev/guide/test-context#annotate}
2389
+ */
2390
+ readonly annotate: {
2391
+ (message: string, type?: string, attachment?: TestAttachment): Promise<TestAnnotation>;
2392
+ (message: string, attachment?: TestAttachment): Promise<TestAnnotation>;
2393
+ };
2394
+ /**
2395
+ * `expect` instance bound to the current test.
2396
+ *
2397
+ * This API is useful for running snapshot tests concurrently because global expect cannot track them.
2398
+ */
2399
+ readonly expect: ExpectStatic;
2400
+ /**
2401
+ * Create a benchmark to run. It will be reported after the test is finished.
2402
+ * @see {@link https://vitest.dev/guide/benchmarking}
2403
+ */
2404
+ readonly bench: Bench;
2405
+ }
2406
+ type OnTestFailedHandler = (context: TestContext) => Awaitable<void>;
2407
+ type OnTestFinishedHandler = (context: TestContext) => Awaitable<void>;
2408
+ interface TaskHook<HookListener> {
2409
+ (fn: HookListener, timeout?: number): void;
2410
+ }
2411
+ type SequenceHooks = "stack" | "list" | "parallel";
2412
+ type SequenceSetupFiles = "list" | "parallel";
2413
+ /**
2414
+ * Represents a file or data attachment associated with a test artifact.
2415
+ *
2416
+ * Attachments can be either path-based (via `path`) or inline content (via `body`).
2417
+ * The `contentType` helps consumers understand how to interpret the attachment data.
2418
+ */
2419
+ interface TestAttachment {
2420
+ /** MIME type of the attachment (e.g., 'image/png', 'text/plain') */
2421
+ contentType?: string;
2422
+ /** Local file path or external HTTP(S) URL to the attachment. Relative paths are resolved from the project root. */
2423
+ path?: string;
2424
+ /** Inline attachment content as a string or raw binary data */
2425
+ body?: string | Uint8Array | undefined;
2426
+ /**
2427
+ * @experimental
2428
+ * How the string `body` is encoded.
2429
+ * - `'base64'` (default): body is already base64-encoded
2430
+ * - `'utf-8'`: body is a utf8 string
2431
+ *
2432
+ * `body: Uint8Array` is always auto-encoded to string with `bodyEncoding: 'base64'`
2433
+ * regardless of this option.
2434
+ */
2435
+ bodyEncoding?: "base64" | "utf-8";
2436
+ }
2437
+ interface Location {
2438
+ /** Line number in the source file (1-indexed) */
2439
+ line: number;
2440
+ /** Column number in the line (1-indexed) */
2441
+ column: number;
2442
+ }
2443
+ interface FileLocation extends Location {
2444
+ /** Line number in the source file (1-indexed) */
2445
+ line: number;
2446
+ /** Column number in the line (1-indexed) */
2447
+ column: number;
2448
+ /** Path to the source file */
2449
+ file: string;
2450
+ }
2451
+ /**
2452
+ * Source code location information for a test artifact.
2453
+ *
2454
+ * Indicates where in the source code the artifact originated from.
2455
+ */
2456
+ interface TestArtifactLocation extends FileLocation {}
2457
+ /**
2458
+ * @experimental
2459
+ *
2460
+ * Base interface for all test artifacts.
2461
+ *
2462
+ * Extend this interface when creating custom test artifacts. Vitest automatically manages the `attachments` array and injects the `location` property to indicate where the artifact was created in your test code.
2463
+ *
2464
+ * **Important**: when running with [`api.allowWrite`](https://vitest.dev/config/api#api-allowwrite) or [`browser.api.allowWrite`](https://vitest.dev/config/browser/api#api-allowwrite) disabled, Vitest empties the `attachments` array on every artifact before reporting it.
2465
+ */
2466
+ interface TestArtifactBase {
2467
+ /** File or data attachments associated with this artifact */
2468
+ attachments?: TestAttachment[];
2469
+ /** Source location where this artifact was created */
2470
+ location?: TestArtifactLocation;
2471
+ }
2472
+ interface TestAnnotation {
2473
+ message: string;
2474
+ type: string;
2475
+ location?: TestArtifactLocation;
2476
+ attachment?: TestAttachment;
2477
+ }
2478
+ /**
2479
+ * @experimental
2480
+ *
2481
+ * Artifact type for test annotations.
2482
+ */
2483
+ interface TestAnnotationArtifact extends TestArtifactBase {
2484
+ type: "internal:annotation";
2485
+ annotation: TestAnnotation;
2486
+ }
2487
+ interface VisualRegressionArtifactAttachment extends TestAttachment {
2488
+ name: "reference" | "actual" | "diff";
2489
+ width: number;
2490
+ height: number;
2491
+ }
2492
+ /**
2493
+ * @experimental
2494
+ *
2495
+ * Artifact type for visual regressions.
2496
+ */
2497
+ interface VisualRegressionArtifact extends TestArtifactBase {
2498
+ type: "internal:toMatchScreenshot";
2499
+ kind: "visual-regression";
2500
+ message: string;
2501
+ attachments: VisualRegressionArtifactAttachment[];
2502
+ }
2503
+ /**
2504
+ * @experimental
2505
+ */
2506
+ interface BrowserTraceArtifact extends TestArtifactBase {
2507
+ type: "internal:browserTrace";
2508
+ data: unknown;
2509
+ }
2510
+ interface FailureScreenshotArtifactAttachment extends TestAttachment {
2511
+ path: string;
2512
+ /** Original file system path to the screenshot, before attachment resolution */
2513
+ originalPath: string;
2514
+ body?: undefined;
2515
+ }
2516
+ /**
2517
+ * @experimental
2518
+ *
2519
+ * Artifact type for failure screenshots.
2520
+ */
2521
+ interface FailureScreenshotArtifact extends TestArtifactBase {
2522
+ type: "internal:failureScreenshot";
2523
+ attachments: [FailureScreenshotArtifactAttachment] | [];
2524
+ }
2525
+ /**
2526
+ * @experimental
2527
+ * @advanced
2528
+ *
2529
+ * Registry for custom test artifact types.
2530
+ *
2531
+ * Augment this interface to register custom artifact types that your tests can produce.
2532
+ *
2533
+ * Each custom artifact should extend {@linkcode TestArtifactBase} and include a unique `type` discriminator property.
2534
+ *
2535
+ * @remarks
2536
+ * - Use a `Symbol` as the **registry key** to guarantee uniqueness
2537
+ * - The `type` property should follow the pattern `'package-name:artifact-name'`, `'internal:'` is a reserved prefix
2538
+ * - Use `attachments` to include files or data; extend {@linkcode TestAttachment} for custom metadata
2539
+ * - `location` property is automatically injected to indicate where the artifact was created
2540
+ *
2541
+ * @example
2542
+ * ```ts
2543
+ * // Define custom attachment type for generated PDF
2544
+ * interface PDFAttachment extends TestAttachment {
2545
+ * contentType: 'application/pdf'
2546
+ * body: Uint8Array
2547
+ * pageCount: number
2548
+ * fileSize: number
2549
+ * }
2550
+ *
2551
+ * interface PDFGenerationArtifact extends TestArtifactBase {
2552
+ * type: 'my-plugin:pdf-generation'
2553
+ * templateName: string
2554
+ * isValid: boolean
2555
+ * attachments: [PDFAttachment]
2556
+ * }
2557
+ *
2558
+ * // Use a symbol to guarantee key uniqueness
2559
+ * const pdfKey = Symbol('pdf-generation')
2560
+ *
2561
+ * declare module 'vitest' {
2562
+ * interface TestArtifactRegistry {
2563
+ * [pdfKey]: PDFGenerationArtifact
2564
+ * }
2565
+ * }
2566
+ *
2567
+ * // Custom assertion for PDF generation
2568
+ * async function toGenerateValidPDF(
2569
+ * this: MatcherState,
2570
+ * actual: PDFTemplate,
2571
+ * data: Record<string, unknown>
2572
+ * ): AsyncExpectationResult {
2573
+ * const pdfBuffer = await actual.render(data)
2574
+ * const validation = await validatePDF(pdfBuffer)
2575
+ *
2576
+ * await recordArtifact(this.task, {
2577
+ * type: 'my-plugin:pdf-generation',
2578
+ * templateName: actual.name,
2579
+ * isValid: validation.success,
2580
+ * attachments: [{
2581
+ * contentType: 'application/pdf',
2582
+ * body: pdfBuffer,
2583
+ * pageCount: validation.pageCount,
2584
+ * fileSize: pdfBuffer.byteLength
2585
+ * }]
2586
+ * })
2587
+ *
2588
+ * return {
2589
+ * pass: validation.success,
2590
+ * message: () => validation.success
2591
+ * ? `Generated valid PDF with ${validation.pageCount} pages`
2592
+ * : `Invalid PDF: ${validation.error}`
2593
+ * }
2594
+ * }
2595
+ * ```
2596
+ */
2597
+ interface TestArtifactRegistry {}
2598
+ /**
2599
+ * @experimental
2600
+ *
2601
+ * Union type of all test artifacts, including built-in and custom registered artifacts.
2602
+ *
2603
+ * This type automatically includes all artifacts registered via {@link TestArtifactRegistry}.
2604
+ */
2605
+ type TestArtifact = BrowserTraceArtifact | FailureScreenshotArtifact | TestAnnotationArtifact | VisualRegressionArtifact | TestArtifactRegistry[keyof TestArtifactRegistry];
2606
+ /**
2607
+ * Possible options to run a single file in a test.
2608
+ */
2609
+ interface FileSpecification {
2610
+ filepath: string;
2611
+ fileTags?: string[];
2612
+ testLocations?: number[] | undefined;
2613
+ testNamePattern?: RegExp | undefined;
2614
+ testTagsFilter?: string[] | undefined;
2615
+ testIds?: string[] | undefined;
2616
+ }
2617
+ type VitestRunnerImportSource = "collect" | "setup";
2618
+ type CancelReason = "keyboard-input" | "test-failure" | (string & Record<string, never>);
2619
+ interface TestTryOptions {
2620
+ retry: number;
2621
+ repeats: number;
2622
+ }
2623
+ interface VitestRunner {
2624
+ /**
2625
+ * First thing that's getting called before actually collecting and running tests.
2626
+ */
2627
+ onBeforeCollect?: (paths: string[]) => unknown;
2628
+ /**
2629
+ * Called after the file task was created but not collected yet.
2630
+ */
2631
+ onCollectStart?: (file: File) => unknown;
2632
+ /**
2633
+ * Called after collecting tests and before "onBeforeRun".
2634
+ */
2635
+ onCollected?: (files: File[]) => unknown;
2636
+ /**
2637
+ * Called when test runner should cancel next test runs.
2638
+ * Runner should listen for this method and mark tests and suites as skipped in
2639
+ * "onBeforeRunSuite" and "onBeforeRunTask" when called.
2640
+ */
2641
+ cancel?: (reason: CancelReason) => unknown;
2642
+ /**
2643
+ * Called before running a single test. Doesn't have "result" yet.
2644
+ */
2645
+ onBeforeRunTask?: (test: Test) => unknown;
2646
+ /**
2647
+ * Called before actually running the test function. Already has "result" with "state" and "startTime".
2648
+ */
2649
+ onBeforeTryTask?: (test: Test, options: TestTryOptions) => unknown;
2650
+ /**
2651
+ * When the task has finished running, but before cleanup hooks are called
2652
+ */
2653
+ onTaskFinished?: (test: Test) => unknown;
2654
+ /**
2655
+ * Called after result and state are set.
2656
+ */
2657
+ onAfterRunTask?: (test: Test) => unknown;
2658
+ /**
2659
+ * Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws.
2660
+ */
2661
+ onAfterTryTask?: (test: Test, options: TestTryOptions) => unknown;
2662
+ /**
2663
+ * Called after the retry resolution happened. Unlike `onAfterTryTask`, the test now has a new state.
2664
+ * All `after` hooks were also called by this point.
2665
+ */
2666
+ onAfterRetryTask?: (test: Test, options: TestTryOptions) => unknown;
2667
+ /**
2668
+ * Called before running a single suite. Doesn't have "result" yet.
2669
+ */
2670
+ onBeforeRunSuite?: (suite: Suite) => unknown;
2671
+ /**
2672
+ * Called after running a single suite. Has state and result.
2673
+ */
2674
+ onAfterRunSuite?: (suite: Suite) => unknown;
2675
+ /**
2676
+ * If defined, will be called instead of usual Vitest suite partition and handling.
2677
+ * "before" and "after" hooks will not be ignored.
2678
+ */
2679
+ runSuite?: (suite: Suite) => Promise<void>;
2680
+ /**
2681
+ * If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function.
2682
+ * "before" and "after" hooks will not be ignored.
2683
+ */
2684
+ runTask?: (test: Test) => Promise<void>;
2685
+ /**
2686
+ * Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests.
2687
+ */
2688
+ onTaskUpdate?: (task: TaskResultPack[], events: TaskEventPack[]) => Promise<void>;
2689
+ /**
2690
+ * Called when annotation is added via the `context.annotate` method.
2691
+ */
2692
+ onTestAnnotate?: (test: Test, annotation: TestAnnotation) => Promise<TestAnnotation>;
2693
+ /**
2694
+ * @experimental
2695
+ *
2696
+ * Called when artifacts are recorded on tests via the `recordArtifact` utility.
2697
+ */
2698
+ onTestArtifactRecord?: <Artifact extends TestArtifact>(test: Test, artifact: Artifact) => Promise<Artifact>;
2699
+ /**
2700
+ * Called before running all tests in collected paths.
2701
+ */
2702
+ onBeforeRunFiles?: (files: File[]) => unknown;
2703
+ /**
2704
+ * Called right after running all tests in collected paths.
2705
+ */
2706
+ onAfterRunFiles?: (files: File[]) => unknown;
2707
+ /**
2708
+ * Called when new context for a test is defined. Useful if you want to add custom properties to the context.
2709
+ * If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead.
2710
+ *
2711
+ * @see https://vitest.dev/advanced/runner#your-task-function
2712
+ */
2713
+ extendTaskContext?: (context: TestContext) => TestContext;
2714
+ /**
2715
+ * Called when test and setup files are imported. Can be called in two situations: when collecting tests and when importing setup files.
2716
+ */
2717
+ importFile: (filepath: string, source: VitestRunnerImportSource) => unknown;
2718
+ /**
2719
+ * Function that is called when the runner attempts to get the value when `test.extend` is used with `{ injected: true }`
2720
+ */
2721
+ injectValue?: (key: string) => unknown;
2722
+ /**
2723
+ * Gets the time spent importing each individual non-externalized file that Vitest collected.
2724
+ */
2725
+ getImportDurations?: () => Record<string, ImportDuration>;
2726
+ /**
2727
+ * Publicly available configuration.
2728
+ */
2729
+ config: SerializedConfig;
2730
+ /**
2731
+ * The name of the current pool. Can affect how stack trace is inferred on the server side.
2732
+ */
2733
+ pool?: string;
2734
+ /**
2735
+ * The current Vite environment that processes the files on the server.
2736
+ */
2737
+ viteEnvironment?: string;
2738
+ onCleanupWorkerContext?: (cleanup: () => unknown) => void;
2739
+ trace?<T>(name: string, cb: () => T): T;
2740
+ trace?<T>(name: string, attributes: Record<string, any>, cb: () => T): T;
2741
+ }
2742
+
2743
+ /**
2744
+ * Config that tests have access to.
2745
+ */
2746
+ interface SerializedConfig {
2747
+ root: string;
2748
+ setupFiles: string[];
2749
+ name: string | undefined;
2750
+ passWithNoTests: boolean;
2751
+ testNamePattern: RegExp | undefined;
2752
+ allowOnly: boolean;
2753
+ sequence: {
2754
+ shuffle?: boolean;
2755
+ concurrent?: boolean;
2756
+ seed: number;
2757
+ hooks: SequenceHooks;
2758
+ setupFiles: SequenceSetupFiles;
2759
+ };
2760
+ maxConcurrency: number;
2761
+ testTimeout: number;
2762
+ hookTimeout: number;
2763
+ retry: SerializableRetry;
2764
+ repeats?: number;
2765
+ includeTaskLocation: boolean | undefined;
2766
+ tags: TestTagDefinition[];
2767
+ tagsFilter: string[] | undefined;
2768
+ strictTags: boolean;
2769
+ color?: LabelColor;
2770
+ globals: boolean;
2771
+ base: string | undefined;
2772
+ snapshotEnvironment?: string;
2773
+ disableConsoleIntercept: boolean | undefined;
2774
+ runner: string | undefined;
2775
+ isolate: boolean;
2776
+ maxWorkers: number;
2777
+ bail: number | undefined;
2778
+ environmentOptions?: Record<string, any>;
2779
+ clearMocks: boolean;
2780
+ mockReset: boolean;
2781
+ restoreMocks: boolean;
2782
+ unstubGlobals: boolean;
2783
+ unstubEnvs: boolean;
2784
+ fakeTimers: Config;
2785
+ defines: Record<string, any>;
2786
+ expect: {
2787
+ requireAssertions?: boolean;
2788
+ poll?: {
2789
+ timeout?: number;
2790
+ interval?: number;
2791
+ };
2792
+ };
2793
+ printConsoleTrace: boolean | undefined;
2794
+ deps: {
2795
+ web: {
2796
+ transformAssets?: boolean;
2797
+ transformCss?: boolean;
2798
+ transformGlobPattern?: RegExp | RegExp[];
2799
+ };
2800
+ optimizer: Record<string, {
2801
+ enabled: boolean;
2802
+ }>;
2803
+ interopDefault: boolean | undefined;
2804
+ moduleDirectories: string[] | undefined;
2805
+ };
2806
+ snapshotOptions: {
2807
+ updateSnapshot: SnapshotUpdateState;
2808
+ expand: boolean | undefined;
2809
+ snapshotFormat: PrettyFormatOptions | undefined;
2810
+ /**
2811
+ * only exists for tests, not available in the main process
2812
+ */
2813
+ snapshotEnvironment: SnapshotEnvironment;
2814
+ };
2815
+ pool: string;
2816
+ snapshotSerializers: string[];
2817
+ chaiConfig: {
2818
+ includeStack?: boolean;
2819
+ showDiff?: boolean;
2820
+ truncateThreshold?: number;
2821
+ } | undefined;
2822
+ taskTitleValueFormatTruncate: number;
2823
+ api: {
2824
+ allowExec: boolean | undefined;
2825
+ allowWrite: boolean | undefined;
2826
+ };
2827
+ diff: string | SerializedDiffOptions | undefined;
2828
+ inspect: boolean | string | undefined;
2829
+ inspectBrk: boolean | string | undefined;
2830
+ inspector: {
2831
+ enabled?: boolean;
2832
+ port?: number;
2833
+ host?: string;
2834
+ waitForDebugger?: boolean;
2835
+ };
2836
+ watch: boolean;
2837
+ env: Record<string, any>;
2838
+ browser: {
2839
+ name: string;
2840
+ headless: boolean;
2841
+ isolate: boolean;
2842
+ fileParallelism: boolean;
2843
+ ui: boolean;
2844
+ viewport: {
2845
+ width: number;
2846
+ height: number;
2847
+ };
2848
+ locators: {
2849
+ testIdAttribute: string;
2850
+ exact: boolean;
2851
+ errorFormat: "html" | "aria" | "all";
2852
+ };
2853
+ screenshotFailures: boolean;
2854
+ providerOptions: {
2855
+ actionTimeout?: number;
2856
+ };
2857
+ trace: BrowserTraceViewMode;
2858
+ traceView: {
2859
+ enabled: boolean;
2860
+ recordCanvas: boolean;
2861
+ inlineImages: boolean;
2862
+ };
2863
+ trackUnhandledErrors: boolean;
2864
+ detailsPanelPosition: "right" | "bottom";
2865
+ };
2866
+ standalone: boolean;
2867
+ logHeapUsage: boolean | undefined;
2868
+ detectAsyncLeaks: boolean;
2869
+ coverage: SerializedCoverageConfig;
2870
+ benchmark: {
2871
+ enabled: boolean;
2872
+ retainSamples: boolean;
2873
+ suppressExportGetterWarnings: boolean;
2874
+ projectName: string;
2875
+ };
2876
+ serializedDefines: string;
2877
+ experimental: {
2878
+ fsModuleCache: boolean;
2879
+ importDurations: {
2880
+ print: boolean | "on-warn";
2881
+ limit: number;
2882
+ failOnDanger: boolean;
2883
+ thresholds: {
2884
+ warn: number;
2885
+ danger: number;
2886
+ };
2887
+ };
2888
+ viteModuleRunner: boolean;
2889
+ nodeLoader: boolean;
2890
+ openTelemetry: {
2891
+ enabled: boolean;
2892
+ sdkPath?: string;
2893
+ browserSdkPath?: string;
2894
+ } | undefined;
2895
+ };
2896
+ mergeReportsLabel: string | undefined;
2897
+ slowTestThreshold: number | undefined;
2898
+ disableColors: boolean;
2899
+ }
2900
+ interface SerializedCoverageConfig {
2901
+ provider: "istanbul" | "v8" | "custom" | undefined;
2902
+ reportsDirectory: string;
2903
+ htmlDir: string | undefined;
2904
+ enabled: boolean;
2905
+ customProviderModule: string | undefined;
2906
+ autoAttachSubprocess: boolean;
2907
+ }
2908
+ interface SerializedRootConfig extends SerializedConfig {
2909
+ projects: SerializedConfig[];
2910
+ }
2911
+ type RuntimeConfig = Pick<SerializedConfig, "allowOnly" | "testTimeout" | "hookTimeout" | "clearMocks" | "mockReset" | "restoreMocks" | "fakeTimers" | "maxConcurrency" | "expect" | "printConsoleTrace"> & {
2912
+ sequence?: {
2913
+ hooks?: SequenceHooks;
2914
+ };
2915
+ };
2916
+ type RuntimeOptions = Partial<RuntimeConfig>;
2917
+ type BrowserTraceViewMode = "on" | "off" | "on-first-retry" | "on-all-retries" | "retain-on-failure";
2918
+
2919
+ export { onTestFailed as aA, onTestFinished as aB, SnapshotState as aE, afterAll as au, afterEach as av, aroundAll as aw, aroundEach as ax, beforeAll as ay, beforeEach as az, createChainable as t };
2920
+ export type { OnTestFinishedHandler as $, AsyncExpectationResult as A, BaselineData as B, Config as C, DomainSnapshotAdapter as D, ExpectStatic as E, File as F, BenchRegistration as G, BenchResult as H, ImportDuration as I, BenchStorage as J, BrowserTraceArtifact as K, LabelColor as L, ModuleGraphData as M, DeeplyAllowMatchers as N, DomainMatchResult as O, ProvidedContext as P, FailureScreenshotArtifact as Q, RuntimeOptions as R, SerializedRootConfig as S, TestAnnotation as T, UserConsoleLog as U, VitestRunner as V, JestAssertion as W, RawMatcherFn as X, Matchers as Y, MatchersObject as Z, OnTestFailedHandler as _, TestArtifact as a, RunMode as a0, TaskBase as a1, TaskResult as a2, RuntimeConfig as a3, SerializedCoverageConfig as a4, SnapshotData as a5, SnapshotMatchOptions as a6, SnapshotResult as a7, SnapshotSerializer as a8, SnapshotStateOptions as a9, SequenceHooks as aC, SequenceSetupFiles as aD, PromisifyAssertion as aF, Tester as aG, FileSpecification as aH, SnapshotEnvironment as aI, SnapshotEnvironmentOptions as aJ, SerializableRetry as aK, AsyncLeak as aL, BrowserTraceViewMode as aM, FetchCachedFileSystemResult as aN, ResolveFunctionResult as aO, SnapshotSummary as aa, SnapshotUpdateState as ab, SuiteFactory as ac, SuiteOptions as ad, TaskCustomOptions as ae, TaskMeta as af, TaskState as ag, TestAnnotationArtifact as ah, TestArtifactBase as ai, TestArtifactLocation as aj, TestArtifactRegistry as ak, TestAttachment as al, TestBenchmark as am, TestBenchmarkTask as an, TestFunction as ao, TestOptions as ap, TestTagDefinition as aq, TestTags as ar, UncheckedSnapshot as as, VisualRegressionArtifact as at, TaskResultPack as b, TaskEventPack as c, Test as d, TaskPopulated as e, MatcherState as f, SyncExpectationResult as g, ExpectationResult as h, TestAPI as i, SuiteCollector as j, SuiteAPI as k, Suite as l, SuiteHooks as m, SerializedConfig as n, VitestRunnerImportSource as o, Task as p, CancelReason as q, TestTryOptions as r, TestContext as s, AfterSuiteRunMeta as u, Assertion as v, AsymmetricMatchersContaining as w, Bench as x, BenchFnOptions as y, BenchFromSource as z };