vitest 4.1.12 → 5.1.0

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 (121) hide show
  1. package/LICENSE.md +192 -10
  2. package/browser/context.d.ts +7 -1
  3. package/browser/context.js +5 -5
  4. package/config.d.ts +0 -2
  5. package/dist/browser.d.ts +52 -21
  6. package/dist/browser.js +12 -13
  7. package/dist/chunks/{acorn.B2iPLyUM.js → acorn.C1kjbUFw.js} +30 -30
  8. package/dist/chunks/{base.B6Opl8PE.js → base.Cof-UHJf.js} +81 -52
  9. package/dist/chunks/{browser.d.BcoexmFG.d.ts → browser.d.C7tWgUvw.d.ts} +17 -14
  10. package/dist/chunks/{cac.DzDtg8hz.js → cac.BYbt0aJp.js} +143 -87
  11. package/dist/chunks/{cli-api.B0Pz1_R7.js → cli-api.COfZo8lK.js} +7160 -7189
  12. package/dist/chunks/config.d.B3YV4t0O.d.ts +3873 -0
  13. package/dist/chunks/{console.3WNpx0tS.js → console.CQZ877Hi.js} +69 -63
  14. package/dist/chunks/{constants.CPYnjOGj.js → constants.DLYM6cZY.js} +2 -2
  15. package/dist/chunks/coverage.9iqXE2gN.js +26 -0
  16. package/dist/chunks/{coverage.CTzCuANN.js → coverage.jGCktcGP.js} +7 -2
  17. package/dist/chunks/{creator.DgVhQm5q.js → creator.DHWmytIK.js} +65 -28
  18. package/dist/chunks/{defaults.9aQKnqFk.js → defaults.B1FCaFfh.js} +16 -9
  19. package/dist/chunks/display.BlTmubjj.js +194 -0
  20. package/dist/chunks/doctor.B-oPbwps.js +465 -0
  21. package/dist/chunks/{env.D4Lgay0q.js → env.BKKtU2WC.js} +2 -1
  22. package/dist/chunks/{environment.d.CrsxCzP1.d.ts → environment.d.BFQtFKdZ.d.ts} +9 -1
  23. package/dist/chunks/globals.ZKtKSkEf.js +29 -0
  24. package/dist/chunks/index.Bi0NXYPf.js +1708 -0
  25. package/dist/chunks/{index.CMESou6r.js → index.BoyTG_B7.js} +82 -81
  26. package/dist/chunks/index.CZzC1gGg.js +8501 -0
  27. package/dist/chunks/index.D0heQG4v.js +1318 -0
  28. package/dist/chunks/index.Di8au7q4.js +15665 -0
  29. package/dist/chunks/{index.Chj8NDwU.js → index.DmDMHCg8.js} +6 -12
  30. package/dist/chunks/{index.DXx9Dtk7.js → index.w_oBZ9N8.js} +25 -12
  31. package/dist/chunks/{init-forks.H5ZuobOQ.js → init-forks.BaDXQSD8.js} +7 -10
  32. package/dist/chunks/{init-threads.6kl1khcL.js → init-threads.ZX_Vov0z.js} +1 -1
  33. package/dist/chunks/{init.k9zZ9sLh.js → init.CO4AB7HZ.js} +113 -38
  34. package/dist/chunks/module-dependencies._2Eei3FO.js +71 -0
  35. package/dist/chunks/{native.DPzPHdi5.js → native.upB-V0CK.js} +50 -37
  36. package/dist/chunks/{nativeModuleMocker.BkNfQMkH.js → nativeModuleMocker.Dh5azSB4.js} +48 -19
  37. package/dist/chunks/{index.BCY_7LL2.js → nativeModuleRunner.9xPIMzi7.js} +110 -42
  38. package/dist/chunks/node.B9mkVmLH.js +47 -0
  39. package/dist/chunks/offset.Dy-5Fdfn.js +24 -0
  40. package/dist/chunks/pathe.M-eThtNZ.zq3TM4NT.js +492 -0
  41. package/dist/chunks/{reporters.d.DtoKVV2s.d.ts → plugin.d.LRFSN46m.d.ts} +2573 -1453
  42. package/dist/chunks/plugins.DPQHVT0p.js +37 -0
  43. package/dist/chunks/rawSnapshot.DqSiqIEx.js +356 -0
  44. package/dist/chunks/resolver.BzpmeQeT.js +48 -0
  45. package/dist/chunks/rpc.Uhkwr2NM.js +93 -0
  46. package/dist/chunks/rpc.d.3FOhdFx8.d.ts +75 -0
  47. package/dist/chunks/run.CjdgFZiW.js +4231 -0
  48. package/dist/chunks/setup-common.CqAQCXzx.js +36 -0
  49. package/dist/chunks/source-map.DakdQc29.js +1788 -0
  50. package/dist/chunks/source-map.d.BkG8YK_3.d.ts +89 -0
  51. package/dist/chunks/spy.DDMXghXv.js +509 -0
  52. package/dist/chunks/task-utils.d.D-gFPNFi.d.ts +144 -0
  53. package/dist/chunks/tinyrainbow.Do8I1XRG.js +88 -0
  54. package/dist/chunks/{utils.BS4fH3nR.js → utils.BBk_icFG.js} +50 -52
  55. package/dist/chunks/{utils.BX5Fg8C4.js → utils.DYj33du9.js} +1 -17
  56. package/dist/chunks/vm.b4MbCAJQ.js +1329 -0
  57. package/dist/chunks/{worker.d.ZpHpO4yb.d.ts → worker.d.CyJRpyfZ.d.ts} +34 -19
  58. package/dist/cli.js +5 -6
  59. package/dist/config.cjs +9 -6
  60. package/dist/config.d.ts +27 -25
  61. package/dist/config.js +3 -3
  62. package/dist/index.d.ts +471 -38
  63. package/dist/index.js +18 -19
  64. package/dist/module-evaluator.d.ts +64 -5
  65. package/dist/module-evaluator.js +122 -62
  66. package/dist/node.d.ts +355 -87
  67. package/dist/node.js +49 -73
  68. package/dist/runtime.d.ts +43 -6
  69. package/dist/runtime.js +7 -9
  70. package/dist/spy.js +1 -1
  71. package/dist/task-utils.js +290 -0
  72. package/dist/{chunks/traces.DT5aQ62U.js → traces.js} +3 -2
  73. package/dist/worker.d.ts +8 -10
  74. package/dist/worker.js +33 -43
  75. package/dist/workers/forks.js +30 -40
  76. package/dist/workers/runVmTests.js +66 -43
  77. package/dist/workers/threads.js +30 -40
  78. package/dist/workers/vmForks.js +19 -20
  79. package/dist/workers/vmThreads.js +19 -20
  80. package/globals.d.ts +19 -19
  81. package/index.cjs +3 -3
  82. package/optional-runtime-types.d.ts +1 -1
  83. package/optional-types.d.ts +1 -1
  84. package/package.json +59 -74
  85. package/suppress-warnings.cjs +1 -1
  86. package/dist/chunks/_commonjsHelpers.D26ty3Ew.js +0 -6
  87. package/dist/chunks/benchmark.CX_oY03V.js +0 -40
  88. package/dist/chunks/benchmark.d.DAaHLpsq.d.ts +0 -24
  89. package/dist/chunks/config.d.A1h_Y6Jt.d.ts +0 -232
  90. package/dist/chunks/coverage.DM_a_rWm.js +0 -1087
  91. package/dist/chunks/coverage.d.BZtK59WP.d.ts +0 -37
  92. package/dist/chunks/evaluatedModules.Dg1zASAC.js +0 -17
  93. package/dist/chunks/global.d.DVsSRdQ5.d.ts +0 -100
  94. package/dist/chunks/globals.Dj1TGiMC.js +0 -31
  95. package/dist/chunks/index.DC7d2Pf8.js +0 -729
  96. package/dist/chunks/index.DdgEv5B1.js +0 -42
  97. package/dist/chunks/index.UpGiHP7g.js +0 -4255
  98. package/dist/chunks/index.og1WyBLx.js +0 -6358
  99. package/dist/chunks/nativeModuleRunner.BIakptoF.js +0 -36
  100. package/dist/chunks/node.COQbm6gK.js +0 -14
  101. package/dist/chunks/plugin.d.DwFIiJ7i.d.ts +0 -38
  102. package/dist/chunks/rpc.MzXet3jl.js +0 -144
  103. package/dist/chunks/rpc.d.B_8sPU0w.d.ts +0 -30
  104. package/dist/chunks/setup-common.DYx3LtFI.js +0 -60
  105. package/dist/chunks/startVitestModuleRunner.DB-7oCpn.js +0 -740
  106. package/dist/chunks/suite.d.udJtyAgw.d.ts +0 -10
  107. package/dist/chunks/test.DNmyFkvJ.js +0 -4430
  108. package/dist/chunks/traces.d.D2T_R8rx.d.ts +0 -60
  109. package/dist/chunks/vm.CXMd5FHa.js +0 -785
  110. package/dist/coverage.d.ts +0 -123
  111. package/dist/coverage.js +0 -27
  112. package/dist/environments.d.ts +0 -22
  113. package/dist/environments.js +0 -5
  114. package/dist/reporters.d.ts +0 -27
  115. package/dist/reporters.js +0 -26
  116. package/dist/runners.d.ts +0 -70
  117. package/dist/runners.js +0 -19
  118. package/dist/snapshot.d.ts +0 -9
  119. package/dist/snapshot.js +0 -6
  120. package/dist/suite.d.ts +0 -5
  121. package/dist/suite.js +0 -8
@@ -0,0 +1,3873 @@
1
+ /// <reference types="chai" />
2
+ import { Disposable } from 'vitest/optional-runtime-types.js';
3
+ import { Fn, FnOptions, BenchOptions as BenchOptions$1, TaskResultCompleted, TaskResultRuntimeInfo, TaskResultTimestampProviderInfo, Statistics } from 'tinybench';
4
+
5
+ /**
6
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
7
+ *
8
+ * This source code is licensed under the MIT license found in the
9
+ * LICENSE file in the root directory of this source tree.
10
+ */
11
+ interface Colors {
12
+ comment: {
13
+ close: string;
14
+ open: string;
15
+ };
16
+ content: {
17
+ close: string;
18
+ open: string;
19
+ };
20
+ prop: {
21
+ close: string;
22
+ open: string;
23
+ };
24
+ tag: {
25
+ close: string;
26
+ open: string;
27
+ };
28
+ value: {
29
+ close: string;
30
+ open: string;
31
+ };
32
+ }
33
+ type Indent = (arg0: string) => string;
34
+ type Refs = Array<unknown>;
35
+ type Print = (arg0: unknown) => string;
36
+ /**
37
+ * compare function used when sorting object keys, `null` can be used to skip over sorting.
38
+ */
39
+ type CompareKeys = ((a: string, b: string) => number) | null | undefined;
40
+ interface PrettyFormatOptions {
41
+ /**
42
+ * Call `toJSON` on objects before formatting them.
43
+ * Ignored after the formatter has already called `toJSON` once for a value.
44
+ * @default true
45
+ */
46
+ callToJSON?: boolean;
47
+ /**
48
+ * Whether to escape special characters in regular expressions.
49
+ * @default false
50
+ */
51
+ escapeRegex?: boolean;
52
+ /**
53
+ * Whether to escape special characters in strings.
54
+ * @default true
55
+ */
56
+ escapeString?: boolean;
57
+ /**
58
+ * Whether to highlight syntax using terminal colors.
59
+ * @default false
60
+ */
61
+ highlight?: boolean;
62
+ /**
63
+ * Number of spaces to use for each level of indentation.
64
+ * @default 2
65
+ */
66
+ indent?: number;
67
+ /**
68
+ * Maximum depth to recurse into nested values.
69
+ * @default Infinity
70
+ */
71
+ maxDepth?: number;
72
+ /**
73
+ * Maximum number of items to print in arrays, sets, maps, and similar collections.
74
+ * @default Infinity
75
+ */
76
+ maxWidth?: number;
77
+ /**
78
+ * Approximate per-depth-level budget for output length.
79
+ * When the accumulated output at any single depth level exceeds this value,
80
+ * further nesting is collapsed. This is a heuristic safety valve, not a hard
81
+ * limit — total output can reach up to roughly `maxDepth × maxOutputLength`.
82
+ * @default 1_000_000
83
+ */
84
+ maxOutputLength?: number;
85
+ /**
86
+ * Whether to minimize added whitespace, including indentation and line breaks.
87
+ *
88
+ * When `true`, pretty-format defaults `spacingInner` to `' '`, `spacingOuter` to `''`,
89
+ * and ignores indentation. It also changes the default for `printBasicPrototype`
90
+ * from `true` to `false`, although an explicit `printBasicPrototype` still wins.
91
+ * Explicit `spacingInner` / `spacingOuter` overrides still apply.
92
+ * @default false
93
+ */
94
+ min?: boolean;
95
+ /**
96
+ * Whether to print `Object` / `Array` prefixes for plain objects and arrays.
97
+ *
98
+ * Defaults to `true`, unless `min` is `true`, in which case it defaults to `false`.
99
+ * An explicit `printBasicPrototype` value always overrides the `min` default.
100
+ */
101
+ printBasicPrototype?: boolean;
102
+ /**
103
+ * Whether to include the function name when formatting functions.
104
+ * @default true
105
+ */
106
+ printFunctionName?: boolean;
107
+ /**
108
+ * Whether to include shadow-root contents when formatting DOM nodes.
109
+ * @default true
110
+ */
111
+ printShadowRoot?: boolean;
112
+ /**
113
+ * Compare function used when sorting object keys. Set to `null` to disable sorting.
114
+ */
115
+ compareKeys?: CompareKeys;
116
+ /**
117
+ * Plugins used to serialize application-specific data types.
118
+ * @default []
119
+ */
120
+ plugins?: Plugins;
121
+ /**
122
+ * Whitespace inserted after commas between items or entries.
123
+ *
124
+ * For example, in `{a: 1, b: 2}` or `[1, 2]`, this controls the gap after each comma:
125
+ * `{a: 1,${spacingInner}b: 2}`
126
+ * `[1,${spacingInner}2]`
127
+ *
128
+ * Defaults to `'\n'` in regular mode and `' '` when `min` is `true`.
129
+ * Can be overridden independently of `min`.
130
+ */
131
+ spacingInner?: string;
132
+ /**
133
+ * Whitespace inserted immediately inside collection/object delimiters.
134
+ *
135
+ * For example, this controls the space or newline right after the opening delimiter
136
+ * and right before the closing delimiter:
137
+ * `{${spacingOuter}a: 1${spacingOuter}}`
138
+ * `[${spacingOuter}1${spacingOuter}]`
139
+ *
140
+ * Defaults to `'\n'` in regular mode and `''` when `min` is `true`.
141
+ * Can be overridden independently of `min`.
142
+ */
143
+ spacingOuter?: string;
144
+ /**
145
+ * Whether to print strings using single quotes instead of double quotes.
146
+ *
147
+ * For example:
148
+ * `"hello"` when `false`
149
+ * `'hello'` when `true`
150
+ *
151
+ * @default false
152
+ */
153
+ singleQuote?: boolean;
154
+ /**
155
+ * Whether to always quote object property keys.
156
+ *
157
+ * For example:
158
+ * `{"a": 1}` when `true`
159
+ * `{a: 1}` when `false` and the key is a valid identifier
160
+ * `{"my-key": 1}` still stays quoted because it is not a valid identifier
161
+ *
162
+ * @default true
163
+ */
164
+ quoteKeys?: boolean;
165
+ }
166
+ type OptionsReceived = PrettyFormatOptions;
167
+ interface Config$1 {
168
+ callToJSON: boolean;
169
+ compareKeys: CompareKeys;
170
+ colors: Colors;
171
+ escapeRegex: boolean;
172
+ escapeString: boolean;
173
+ indent: string;
174
+ maxDepth: number;
175
+ maxWidth: number;
176
+ min: boolean;
177
+ plugins: Plugins;
178
+ printBasicPrototype: boolean;
179
+ printFunctionName: boolean;
180
+ printShadowRoot: boolean;
181
+ spacingInner: string;
182
+ spacingOuter: string;
183
+ singleQuote: boolean;
184
+ quoteKeys: boolean;
185
+ maxOutputLength: number;
186
+ }
187
+ type Printer = (val: unknown, config: Config$1, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string;
188
+ type Test$1 = (arg0: any) => boolean;
189
+ interface NewPlugin {
190
+ serialize: (val: any, config: Config$1, indentation: string, depth: number, refs: Refs, printer: Printer) => string;
191
+ test: Test$1;
192
+ }
193
+ interface PluginOptions {
194
+ edgeSpacing: string;
195
+ min: boolean;
196
+ spacing: string;
197
+ }
198
+ interface OldPlugin {
199
+ print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string;
200
+ test: Test$1;
201
+ }
202
+ type Plugin = NewPlugin | OldPlugin;
203
+ type Plugins = Array<Plugin>;
204
+
205
+ interface StringifyOptions extends PrettyFormatOptions {
206
+ maxLength?: number;
207
+ filterNode?: string | ((node: any) => boolean);
208
+ }
209
+ declare function stringify(object: unknown, maxDepth?: number, { maxLength, filterNode, ...options }?: StringifyOptions): string;
210
+ declare function format(args: unknown[], options?: InspectOptions): string;
211
+ interface InspectOptions extends StringifyOptions {
212
+ truncate?: number;
213
+ multiline?: boolean;
214
+ }
215
+ declare function inspect(obj: unknown, options?: InspectOptions): string;
216
+
217
+ type Awaitable<T> = T | PromiseLike<T>;
218
+ type Arrayable<T> = T | Array<T>;
219
+ interface ParsedStack {
220
+ method: string;
221
+ file: string;
222
+ line: number;
223
+ column: number;
224
+ }
225
+ interface SerializedError {
226
+ message: string;
227
+ stacks?: ParsedStack[];
228
+ stack?: string;
229
+ name?: string;
230
+ cause?: SerializedError;
231
+ [key: string]: unknown;
232
+ }
233
+ interface TestError extends SerializedError {
234
+ cause?: TestError;
235
+ diff?: string;
236
+ actual?: string;
237
+ expected?: string;
238
+ }
239
+
240
+ interface DomainMatchResult {
241
+ pass: boolean;
242
+ message?: string;
243
+ /**
244
+ * The captured value viewed through the template's lens.
245
+ *
246
+ * Where the template uses patterns (e.g. regexes) or omits details,
247
+ * the resolved string adopts those patterns. Where the template doesn't
248
+ * match, the resolved string uses literal captured values instead.
249
+ *
250
+ * Used for two purposes:
251
+ * - **Diff display** (actual side): compared against `expected`
252
+ * so the diff highlights only genuine mismatches, not pattern-vs-literal noise.
253
+ * - **Snapshot update** (`--update`): written as the new snapshot content,
254
+ * preserving user-edited patterns from matched regions while incorporating
255
+ * actual values for mismatched regions.
256
+ *
257
+ * When omitted, falls back to `render(capture(received))` (the raw rendered value).
258
+ */
259
+ resolved?: string;
260
+ /**
261
+ * The stored template re-rendered as a string, representing what the user
262
+ * originally wrote or last saved.
263
+ *
264
+ * Used as the expected side in diff display.
265
+ *
266
+ * When omitted, falls back to the raw snapshot string from the snap file
267
+ * or inline snapshot.
268
+ */
269
+ expected?: string;
270
+ }
271
+ interface DomainSnapshotAdapter<
272
+ Captured = unknown,
273
+ Expected = unknown
274
+ > {
275
+ name: string;
276
+ capture: (received: unknown) => Captured;
277
+ render: (captured: Captured) => string;
278
+ parseExpected: (input: string) => Expected;
279
+ match: (captured: Captured, expected: Expected) => DomainMatchResult;
280
+ }
281
+
282
+ interface RawSnapshotInfo {
283
+ file: string;
284
+ readonly?: boolean;
285
+ content?: string;
286
+ }
287
+ interface RawSnapshot extends RawSnapshotInfo {
288
+ snapshot: string;
289
+ }
290
+
291
+ interface InlineSnapshot {
292
+ snapshot: string;
293
+ testId: string;
294
+ file: string;
295
+ line: number;
296
+ column: number;
297
+ assertionName?: string;
298
+ }
299
+
300
+ interface InlineSnapshotUpdate extends InlineSnapshot {
301
+ type: "inline";
302
+ }
303
+ interface FileSnapshotUpdate {
304
+ type: "file";
305
+ file: string;
306
+ key: string;
307
+ snapshot: string;
308
+ }
309
+ interface RawSnapshotUpdate extends RawSnapshot {
310
+ type: "raw";
311
+ }
312
+ type SnapshotUpdate = InlineSnapshotUpdate | FileSnapshotUpdate | RawSnapshotUpdate;
313
+
314
+ interface SnapshotEnvironment {
315
+ getVersion: () => string;
316
+ getHeader: () => string;
317
+ resolvePath: (filepath: string) => Promise<string>;
318
+ resolveRawPath: (testPath: string, rawPath: string) => Promise<string>;
319
+ saveSnapshotFile: (filepath: string, snapshot: string) => Promise<void>;
320
+ readSnapshotFile: (filepath: string) => Promise<string | null>;
321
+ readSnapshotFileData?: (filepath: string) => Promise<Record<string, string> | null>;
322
+ removeSnapshotFile: (filepath: string) => Promise<void>;
323
+ processStackTrace?: (stack: ParsedStack) => ParsedStack;
324
+ }
325
+ interface SnapshotEnvironmentOptions {
326
+ snapshotsDirName?: string;
327
+ }
328
+ declare class DefaultMap<
329
+ K,
330
+ V
331
+ > extends Map<K, V> {
332
+ private defaultFn;
333
+ constructor(defaultFn: (key: K) => V, entries?: Iterable<readonly [K, V]>);
334
+ override get(key: K): V;
335
+ }
336
+ declare class CounterMap<K> extends DefaultMap<K, number> {
337
+ constructor();
338
+ _total: number | undefined;
339
+ valueOf(): number;
340
+ increment(key: K): void;
341
+ total(): number;
342
+ }
343
+
344
+ interface SnapshotReturnOptions {
345
+ actual: string;
346
+ count: number;
347
+ expected?: string;
348
+ key: string;
349
+ pass: boolean;
350
+ update?: SnapshotUpdate;
351
+ }
352
+ interface SaveStatus {
353
+ deleted: boolean;
354
+ saved: boolean;
355
+ }
356
+ interface ExpectedSnapshot {
357
+ key: string;
358
+ count: number;
359
+ data?: string;
360
+ markAsChecked: () => void;
361
+ }
362
+ declare class SnapshotState {
363
+ testFilePath: string;
364
+ snapshotPath: string;
365
+ private _counters;
366
+ private _dirty;
367
+ private _updateSnapshot;
368
+ private _snapshotData;
369
+ private _initialData;
370
+ private _inlineSnapshots;
371
+ private _inlineSnapshotStacks;
372
+ private _testIdToKeys;
373
+ private _rawSnapshots;
374
+ private _rawSnapshotFiles;
375
+ private _uncheckedKeys;
376
+ private _snapshotFormat;
377
+ private _environment;
378
+ private _fileExists;
379
+ expand: boolean;
380
+ private _added;
381
+ private _matched;
382
+ private _unmatched;
383
+ private _updated;
384
+ get added(): CounterMap<string>;
385
+ set added(value: number);
386
+ get matched(): CounterMap<string>;
387
+ set matched(value: number);
388
+ get unmatched(): CounterMap<string>;
389
+ set unmatched(value: number);
390
+ get updated(): CounterMap<string>;
391
+ set updated(value: number);
392
+ private constructor();
393
+ static create(testFilePath: string, options: SnapshotStateOptions): Promise<SnapshotState>;
394
+ get snapshotUpdateState(): SnapshotUpdateState;
395
+ get environment(): SnapshotEnvironment;
396
+ markSnapshotsAsCheckedForTest(testName: string): void;
397
+ clearTest(testId: string): void;
398
+ protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null;
399
+ private _addSnapshot;
400
+ private _resolveKey;
401
+ private _resolveInlineStack;
402
+ private _reconcile;
403
+ private _createUpdate;
404
+ save(): Promise<SaveStatus>;
405
+ getUncheckedCount(): number;
406
+ getUncheckedKeys(): Array<string>;
407
+ removeUncheckedKeys(): void;
408
+ probeExpectedSnapshot(options: Pick<SnapshotMatchOptions, "testName" | "testId" | "isInline" | "inlineSnapshot">): ExpectedSnapshot;
409
+ match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot, assertionName }: SnapshotMatchOptions): SnapshotReturnOptions;
410
+ processDomainSnapshot({ testId, received, expectedSnapshot, matchResult, isInline, error, assertionName }: ProcessDomainSnapshotOptions): SnapshotReturnOptions;
411
+ /**
412
+ * The snapshot file, if the test file stores snapshots in it, and every asserted file snapshot.
413
+ */
414
+ getSnapshotFiles(): string[];
415
+ pack(): Promise<SnapshotResult>;
416
+ }
417
+
418
+ type SnapshotData = Record<string, string>;
419
+ type SnapshotUpdateState = "all" | "new" | "none";
420
+ type SnapshotSerializer = Plugin;
421
+ interface SnapshotStateOptions {
422
+ updateSnapshot: SnapshotUpdateState;
423
+ snapshotEnvironment: SnapshotEnvironment;
424
+ expand?: boolean;
425
+ snapshotFormat?: OptionsReceived;
426
+ resolveSnapshotPath?: (path: string, extension: string, context?: any) => string;
427
+ }
428
+ interface SnapshotMatchOptions {
429
+ testId: string;
430
+ testName: string;
431
+ received: unknown;
432
+ key?: string;
433
+ inlineSnapshot?: string;
434
+ isInline: boolean;
435
+ error?: Error;
436
+ rawSnapshot?: RawSnapshotInfo;
437
+ assertionName?: string;
438
+ }
439
+ interface ProcessDomainSnapshotOptions {
440
+ testId: string;
441
+ received: string;
442
+ expectedSnapshot: ExpectedSnapshot;
443
+ matchResult?: DomainMatchResult;
444
+ isInline?: boolean;
445
+ assertionName?: string;
446
+ error?: Error;
447
+ }
448
+ interface SnapshotResult {
449
+ filepath: string;
450
+ added: number;
451
+ fileDeleted: boolean;
452
+ matched: number;
453
+ unchecked: number;
454
+ uncheckedKeys: Array<string>;
455
+ unmatched: number;
456
+ updated: number;
457
+ }
458
+ interface UncheckedSnapshot {
459
+ filePath: string;
460
+ keys: Array<string>;
461
+ }
462
+ interface SnapshotSummary {
463
+ added: number;
464
+ didUpdate: boolean;
465
+ failure: boolean;
466
+ filesAdded: number;
467
+ filesRemoved: number;
468
+ filesRemovedList: Array<string>;
469
+ filesUnmatched: number;
470
+ filesUpdated: number;
471
+ matched: number;
472
+ total: number;
473
+ unchecked: number;
474
+ uncheckedKeysByFile: Array<UncheckedSnapshot>;
475
+ unmatched: number;
476
+ updated: number;
477
+ }
478
+
479
+ /**
480
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
481
+ *
482
+ * This source code is licensed under the MIT license found in the
483
+ * LICENSE file in the root directory of this source tree.
484
+ */
485
+
486
+ type DiffOptionsColor = (arg: string) => string;
487
+ interface DiffOptions {
488
+ aAnnotation?: string;
489
+ aColor?: DiffOptionsColor;
490
+ aIndicator?: string;
491
+ bAnnotation?: string;
492
+ bColor?: DiffOptionsColor;
493
+ bIndicator?: string;
494
+ changeColor?: DiffOptionsColor;
495
+ changeLineTrailingSpaceColor?: DiffOptionsColor;
496
+ commonColor?: DiffOptionsColor;
497
+ commonIndicator?: string;
498
+ commonLineTrailingSpaceColor?: DiffOptionsColor;
499
+ contextLines?: number;
500
+ emptyFirstOrLastLinePlaceholder?: string;
501
+ expand?: boolean;
502
+ includeChangeCounts?: boolean;
503
+ omitAnnotationLines?: boolean;
504
+ patchColor?: DiffOptionsColor;
505
+ printBasicPrototype?: boolean;
506
+ maxDepth?: number;
507
+ compareKeys?: CompareKeys;
508
+ truncateThreshold?: number;
509
+ truncateAnnotation?: string;
510
+ truncateAnnotationColor?: DiffOptionsColor;
511
+ }
512
+ interface SerializedDiffOptions {
513
+ aAnnotation?: string;
514
+ aIndicator?: string;
515
+ bAnnotation?: string;
516
+ bIndicator?: string;
517
+ commonIndicator?: string;
518
+ contextLines?: number;
519
+ emptyFirstOrLastLinePlaceholder?: string;
520
+ expand?: boolean;
521
+ includeChangeCounts?: boolean;
522
+ omitAnnotationLines?: boolean;
523
+ printBasicPrototype?: boolean;
524
+ maxDepth?: number;
525
+ truncateThreshold?: number;
526
+ truncateAnnotation?: string;
527
+ }
528
+
529
+ /**
530
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
531
+ *
532
+ * This source code is licensed under the MIT license found in the
533
+ * LICENSE file in the root directory of this source tree.
534
+ */
535
+
536
+ interface StringifiedMemory {
537
+ expected?: string;
538
+ actual?: string;
539
+ }
540
+ interface Memorize {
541
+ (pointer: "expected" | "actual", stringifiedValue: string): string;
542
+ }
543
+ /**
544
+ * @param a Expected value
545
+ * @param b Received value
546
+ * @param options Diff options
547
+ * @returns {string | null} a string diff
548
+ */
549
+ declare function diff(a: any, b: any, options?: DiffOptions, memorize?: Memorize): string | undefined;
550
+ declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions, memory?: StringifiedMemory): string | undefined;
551
+
552
+ type VoidVarArgsFunc = (...args: unknown[]) => void;
553
+ type SetImmediate = (callback: VoidVarArgsFunc, ...args: unknown[]) => NodeImmediate;
554
+ type SetTimeout = (callback: VoidVarArgsFunc, delay?: number, ...args: unknown[]) => TimerId;
555
+ type ClearTimeout = (id?: TimerId) => void;
556
+ type SetInterval = (callback: VoidVarArgsFunc, delay?: number, ...args: unknown[]) => TimerId;
557
+ type ClearInterval = (id?: TimerId) => void;
558
+ type QueueMicrotask = (callback: VoidVarArgsFunc) => void;
559
+ type TimeRemaining = () => number;
560
+ type IdleDeadline = {
561
+ didTimeout: boolean;
562
+ timeRemaining: TimeRemaining;
563
+ };
564
+ type RequestIdleCallbackCallback = (deadline: IdleDeadline) => any;
565
+ type RequestIdleCallback = (callback: RequestIdleCallbackCallback, options?: {
566
+ timeout?: number;
567
+ }) => number;
568
+ type AnimationFrameCallback = (timestamp: number) => any;
569
+ type RequestAnimationFrame = (callback: AnimationFrameCallback) => TimerId;
570
+ type CancelAnimationFrame = (id: TimerId) => void;
571
+ type CancelIdleCallback = (id: TimerId) => void;
572
+ type ClearImmediate = (id: NodeImmediate) => void;
573
+ type TemporalTimelike = {
574
+ epochMilliseconds: number;
575
+ };
576
+ type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime" | "requestAnimationFrame" | "cancelAnimationFrame" | "requestIdleCallback" | "cancelIdleCallback" | "performance" | "queueMicrotask" | "Intl" | "Temporal";
577
+ type TimerId = number | NodeImmediate | Timer;
578
+ type GlobalObject = Record<string, any> & {
579
+ setTimeout?: SetTimeout;
580
+ clearTimeout?: ClearTimeout;
581
+ setInterval?: SetInterval;
582
+ clearInterval?: ClearInterval;
583
+ setImmediate?: SetImmediate;
584
+ clearImmediate?: ClearImmediate;
585
+ queueMicrotask?: QueueMicrotask;
586
+ requestAnimationFrame?: RequestAnimationFrame;
587
+ cancelAnimationFrame?: CancelAnimationFrame;
588
+ requestIdleCallback?: RequestIdleCallback;
589
+ cancelIdleCallback?: CancelIdleCallback;
590
+ process?: any;
591
+ performance?: any;
592
+ Performance?: any;
593
+ Intl?: any;
594
+ Temporal?: any;
595
+ Promise?: typeof Promise;
596
+ Date: typeof Date & {
597
+ isFake?: boolean;
598
+ toSource?: () => string;
599
+ clock?: any;
600
+ };
601
+ };
602
+ type TimerInitialProps = {
603
+ func: VoidVarArgsFunc;
604
+ args?: unknown[];
605
+ type?: 'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback';
606
+ delay?: number;
607
+ callAt?: number;
608
+ createdAt?: number;
609
+ immediate?: boolean;
610
+ id?: number;
611
+ error?: Error;
612
+ interval?: number;
613
+ animation?: boolean;
614
+ requestIdleCallback?: boolean;
615
+ order?: number;
616
+ heapIndex?: number;
617
+ };
618
+ type Config = {
619
+ now?: number | Date | TemporalTimelike;
620
+ toFake?: FakeMethod[];
621
+ toNotFake?: FakeMethod[];
622
+ loopLimit?: number;
623
+ shouldAdvanceTime?: boolean;
624
+ advanceTimeDelta?: number;
625
+ shouldClearNativeTimers?: boolean;
626
+ ignoreMissingTimers?: boolean;
627
+ target?: GlobalObject;
628
+ };
629
+ type Timer = TimerInitialProps;
630
+ type NodeImmediateHasRef = () => boolean;
631
+ type NodeImmediateRef = () => NodeImmediate;
632
+ type NodeImmediateUnref = () => NodeImmediate;
633
+ type NodeImmediate = {
634
+ hasRef: NodeImmediateHasRef;
635
+ ref: NodeImmediateRef;
636
+ unref: NodeImmediateUnref;
637
+ };
638
+
639
+ /**
640
+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
641
+ *
642
+ * This source code is licensed under the MIT license found in the
643
+ * LICENSE file in the root directory of https://github.com/jestjs/jest.
644
+ */
645
+
646
+ interface FakeTimersConfig extends Config {
647
+ /**
648
+ * Mock timer APIs imported from `node:timers` and `node:timers/promises`.
649
+ *
650
+ * @default false
651
+ */
652
+ fakeNodeBuiltins?: boolean;
653
+ }
654
+
655
+ interface AfterSuiteRunMeta {
656
+ coverage?: unknown;
657
+ testFiles: string[];
658
+ environment: string;
659
+ projectName?: string;
660
+ }
661
+ interface UserConsoleLog {
662
+ content: string;
663
+ origin?: string;
664
+ browser?: boolean;
665
+ type: "stdout" | "stderr";
666
+ taskId?: string;
667
+ time: number;
668
+ size: number;
669
+ }
670
+ interface ModuleGraphModules {
671
+ [id: string]: {
672
+ external: boolean;
673
+ imports: string[];
674
+ };
675
+ }
676
+ interface ModuleGraphData {
677
+ modules: ModuleGraphModules;
678
+ roots: string[];
679
+ }
680
+ interface ProvidedContext {}
681
+ interface ResolveFunctionResult {
682
+ id: string;
683
+ file: string;
684
+ url: string;
685
+ }
686
+ type ModuleType = "cjs" | "esm";
687
+ interface FetchCachedFileSystemResult {
688
+ cached: true;
689
+ tmp: string;
690
+ id: string;
691
+ file: string | null;
692
+ url: string;
693
+ invalidate: boolean;
694
+ moduleType?: ModuleType;
695
+ }
696
+ type LabelColor = "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white";
697
+ interface AsyncLeak {
698
+ filename: string;
699
+ projectName: string;
700
+ stack: string;
701
+ type: string;
702
+ }
703
+
704
+ interface MockResultReturn<T> {
705
+ type: "return";
706
+ /**
707
+ * The value that was returned from the function. If the function returned a Promise, then this will be the Promise, not its resolved value.
708
+ */
709
+ value: T;
710
+ }
711
+ interface MockResultIncomplete {
712
+ type: "incomplete";
713
+ value: undefined;
714
+ }
715
+ interface MockResultThrow {
716
+ type: "throw";
717
+ /**
718
+ * An error that was thrown during function execution.
719
+ */
720
+ value: any;
721
+ }
722
+ interface MockSettledResultIncomplete {
723
+ type: "incomplete";
724
+ value: undefined;
725
+ }
726
+ interface MockSettledResultFulfilled<T> {
727
+ type: "fulfilled";
728
+ value: T;
729
+ }
730
+ interface MockSettledResultRejected {
731
+ type: "rejected";
732
+ value: any;
733
+ }
734
+ type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
735
+ type MockSettledResult<T> = MockSettledResultFulfilled<T> | MockSettledResultRejected | MockSettledResultIncomplete;
736
+ type MockParameters<T extends Procedure | Constructable> = T extends Constructable ? ConstructorParameters<T> : T extends Procedure ? Parameters<T> : never;
737
+ type MockReturnType<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : T extends Procedure ? ReturnType<T> : never;
738
+ type MockProcedureContext<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : ThisParameterType<T>;
739
+ interface MockContext<T extends Procedure | Constructable = Procedure> {
740
+ /**
741
+ * This is an array containing all arguments for each call. One item of the array is the arguments of that call.
742
+ *
743
+ * @see https://vitest.dev/api/mock#mock-calls
744
+ * @example
745
+ * const fn = vi.fn()
746
+ *
747
+ * fn('arg1', 'arg2')
748
+ * fn('arg3')
749
+ *
750
+ * fn.mock.calls === [
751
+ * ['arg1', 'arg2'], // first call
752
+ * ['arg3'], // second call
753
+ * ]
754
+ */
755
+ calls: MockParameters<T>[];
756
+ /**
757
+ * An array with one value for each call: the object returned by `new`, or the context (`this`) of the call if the mock was called without `new`.
758
+ * @see https://vitest.dev/api/mock#mock-instances
759
+ */
760
+ instances: MockProcedureContext<T>[];
761
+ /**
762
+ * An array of `this` values that were used during each call to the mock function. If the mock was called with `new`, the value is the same as in `instances`.
763
+ * @see https://vitest.dev/api/mock#mock-contexts
764
+ */
765
+ contexts: MockProcedureContext<T>[];
766
+ /**
767
+ * The order of mock's execution. This returns an array of numbers which are shared between all defined mocks.
768
+ *
769
+ * @see https://vitest.dev/api/mock#mock-invocationcallorder
770
+ * @example
771
+ * const fn1 = vi.fn()
772
+ * const fn2 = vi.fn()
773
+ *
774
+ * fn1()
775
+ * fn2()
776
+ * fn1()
777
+ *
778
+ * fn1.mock.invocationCallOrder === [1, 3]
779
+ * fn2.mock.invocationCallOrder === [2]
780
+ */
781
+ invocationCallOrder: number[];
782
+ /**
783
+ * This is an array containing all values that were `returned` from the function.
784
+ *
785
+ * The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected.
786
+ *
787
+ * @see https://vitest.dev/api/mock#mock-results
788
+ * @example
789
+ * const fn = vi.fn()
790
+ * .mockReturnValueOnce('result')
791
+ * .mockImplementationOnce(() => { throw new Error('thrown error') })
792
+ *
793
+ * const result = fn()
794
+ *
795
+ * try {
796
+ * fn()
797
+ * }
798
+ * catch {}
799
+ *
800
+ * fn.mock.results === [
801
+ * {
802
+ * type: 'return',
803
+ * value: 'result',
804
+ * },
805
+ * {
806
+ * type: 'throw',
807
+ * value: Error,
808
+ * },
809
+ * ]
810
+ */
811
+ results: MockResult<MockReturnType<T>>[];
812
+ /**
813
+ * An array containing all values that were `resolved` or `rejected` from the function.
814
+ *
815
+ * Until the value is resolved or rejected, the type will be `incomplete`.
816
+ *
817
+ * @see https://vitest.dev/api/mock#mock-settledresults
818
+ * @example
819
+ * const fn = vi.fn().mockResolvedValueOnce('result')
820
+ *
821
+ * const result = fn()
822
+ *
823
+ * fn.mock.settledResults === [
824
+ * {
825
+ * type: 'incomplete',
826
+ * value: undefined,
827
+ * }
828
+ * ]
829
+ * fn.mock.results === [
830
+ * {
831
+ * type: 'return',
832
+ * value: Promise<'result'>,
833
+ * },
834
+ * ]
835
+ *
836
+ * await result
837
+ *
838
+ * fn.mock.settledResults === [
839
+ * {
840
+ * type: 'fulfilled',
841
+ * value: 'result',
842
+ * },
843
+ * ]
844
+ */
845
+ settledResults: MockSettledResult<Awaited<MockReturnType<T>>>[];
846
+ /**
847
+ * This contains the arguments of the last call. If spy wasn't called, will return `undefined`.
848
+ * @see https://vitest.dev/api/mock#mock-lastcall
849
+ */
850
+ lastCall: MockParameters<T> | undefined;
851
+ }
852
+ type Procedure = (...args: any[]) => any;
853
+ type NormalizedProcedure<T extends Procedure | Constructable> = T extends Constructable ? {
854
+ new (...args: ConstructorParameters<T>): InstanceType<T>;
855
+ } | {
856
+ (this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
857
+ } : T extends Procedure ? (...args: Parameters<T>) => ReturnType<T> : never;
858
+ type Methods<T> = keyof { [K in keyof T as T[K] extends Procedure ? K : never]: T[K] };
859
+ type Properties<T> = { [K in keyof T]: T[K] extends Procedure ? never : K }[keyof T] & (string | symbol);
860
+ type Classes<T> = { [K in keyof T]: T[K] extends new (...args: any[]) => any ? K : never }[keyof T] & (string | symbol);
861
+ interface MockInstance<T extends Procedure | Constructable = Procedure> extends Disposable {
862
+ /**
863
+ * Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`.
864
+ * @see https://vitest.dev/api/mock#getmockname
865
+ */
866
+ getMockName(): string;
867
+ /**
868
+ * Sets the internal mock name. This is useful for identifying the mock when an assertion fails.
869
+ * @see https://vitest.dev/api/mock#mockname
870
+ */
871
+ mockName(name: string): this;
872
+ /**
873
+ * Current context of the mock. It stores information about all invocation calls, instances, and results.
874
+ */
875
+ mock: MockContext<T>;
876
+ /**
877
+ * Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions.
878
+ *
879
+ * To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/clearmocks) setting in the configuration.
880
+ * @see https://vitest.dev/api/mock#mockclear
881
+ */
882
+ mockClear(): this;
883
+ /**
884
+ * Does what `mockClear` does and resets inner implementation to the original function. This also resets all "once" implementations.
885
+ *
886
+ * Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`.
887
+ * Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state.
888
+ *
889
+ * To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/mockreset) setting in the configuration.
890
+ * @see https://vitest.dev/api/mock#mockreset
891
+ */
892
+ mockReset(): this;
893
+ /**
894
+ * Does what `mockReset` does and restores original descriptors of spied-on objects.
895
+ * @see https://vitest.dev/api/mock#mockrestore
896
+ */
897
+ mockRestore(): void;
898
+ /**
899
+ * Returns current mock implementation if there is one. If an implementation was queued with `mockImplementationOnce`, it returns the first queued implementation instead.
900
+ *
901
+ * If mock was created with `vi.fn`, it will consider passed down method as a mock implementation.
902
+ *
903
+ * If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided.
904
+ */
905
+ getMockImplementation(): NormalizedProcedure<T> | undefined;
906
+ /**
907
+ * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function.
908
+ * @see https://vitest.dev/api/mock#mockimplementation
909
+ * @example
910
+ * const increment = vi.fn().mockImplementation(count => count + 1);
911
+ * expect(increment(3)).toBe(4);
912
+ */
913
+ mockImplementation(fn: NormalizedProcedure<T>): this;
914
+ /**
915
+ * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls.
916
+ *
917
+ * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called.
918
+ * @see https://vitest.dev/api/mock#mockimplementationonce
919
+ * @example
920
+ * const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1);
921
+ * expect(fn(3)).toBe(4);
922
+ * expect(fn(3)).toBe(3);
923
+ */
924
+ mockImplementationOnce(fn: NormalizedProcedure<T>): this;
925
+ /**
926
+ * Overrides the original mock implementation temporarily while the callback is being executed.
927
+ *
928
+ * Note that this method takes precedence over the [`mockImplementationOnce`](https://vitest.dev/api/mock#mockimplementationonce).
929
+ * @see https://vitest.dev/api/mock#withimplementation
930
+ * @example
931
+ * const myMockFn = vi.fn(() => 'original')
932
+ *
933
+ * myMockFn.withImplementation(() => 'temp', () => {
934
+ * myMockFn() // 'temp'
935
+ * })
936
+ *
937
+ * myMockFn() // 'original'
938
+ */
939
+ withImplementation(fn: NormalizedProcedure<T>, cb: () => Promise<unknown>): Promise<this>;
940
+ withImplementation(fn: NormalizedProcedure<T>, cb: () => unknown): this;
941
+ /**
942
+ * Use this if you need to return the `this` context from the method without invoking the actual implementation.
943
+ * @see https://vitest.dev/api/mock#mockreturnthis
944
+ */
945
+ mockReturnThis(): this;
946
+ /**
947
+ * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
948
+ * @see https://vitest.dev/api/mock#mockreturnvalue
949
+ * @example
950
+ * const mock = vi.fn()
951
+ * mock.mockReturnValue(42)
952
+ * mock() // 42
953
+ * mock.mockReturnValue(43)
954
+ * mock() // 43
955
+ */
956
+ mockReturnValue(value: MockReturnType<T>): this;
957
+ /**
958
+ * Accepts a value that will be returned during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will return the specified value.
959
+ *
960
+ * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called.
961
+ * @example
962
+ * const myMockFn = vi
963
+ * .fn()
964
+ * .mockReturnValue('default')
965
+ * .mockReturnValueOnce('first call')
966
+ * .mockReturnValueOnce('second call')
967
+ *
968
+ * // 'first call', 'second call', 'default'
969
+ * console.log(myMockFn(), myMockFn(), myMockFn())
970
+ */
971
+ mockReturnValueOnce(value: MockReturnType<T>): this;
972
+ /**
973
+ * Accepts a value that will be thrown whenever the mock function is called.
974
+ * @see https://vitest.dev/api/mock#mockthrow
975
+ * @example
976
+ * const myMockFn = vi.fn().mockThrow(new Error('error'))
977
+ * myMockFn() // throws 'error'
978
+ */
979
+ mockThrow(value: unknown): this;
980
+ /**
981
+ * Accepts a value that will be thrown during the next function call. If chained, every consecutive call will throw the specified value.
982
+ * @example
983
+ * const myMockFn = vi
984
+ * .fn()
985
+ * .mockReturnValue('default')
986
+ * .mockThrowOnce(new Error('first call error'))
987
+ * .mockThrowOnce('second call error')
988
+ *
989
+ * expect(() => myMockFn()).toThrowError('first call error')
990
+ * expect(() => myMockFn()).toThrowError('second call error')
991
+ * expect(myMockFn()).toEqual('default')
992
+ */
993
+ mockThrowOnce(value: unknown): this;
994
+ /**
995
+ * Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function.
996
+ * @example
997
+ * const asyncMock = vi.fn().mockResolvedValue(42)
998
+ * asyncMock() // Promise<42>
999
+ */
1000
+ mockResolvedValue(value: Awaited<MockReturnType<T>>): this;
1001
+ /**
1002
+ * Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value.
1003
+ * @example
1004
+ * const myMockFn = vi
1005
+ * .fn()
1006
+ * .mockResolvedValue('default')
1007
+ * .mockResolvedValueOnce('first call')
1008
+ * .mockResolvedValueOnce('second call')
1009
+ *
1010
+ * // Promise<'first call'>, Promise<'second call'>, Promise<'default'>
1011
+ * console.log(myMockFn(), myMockFn(), myMockFn())
1012
+ */
1013
+ mockResolvedValueOnce(value: Awaited<MockReturnType<T>>): this;
1014
+ /**
1015
+ * Accepts an error that will be rejected when async function is called.
1016
+ * @example
1017
+ * const asyncMock = vi.fn().mockRejectedValue(new Error('Async error'))
1018
+ * await asyncMock() // throws Error<'Async error'>
1019
+ */
1020
+ mockRejectedValue(error: unknown): this;
1021
+ /**
1022
+ * Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value.
1023
+ * @example
1024
+ * const asyncMock = vi
1025
+ * .fn()
1026
+ * .mockResolvedValueOnce('first call')
1027
+ * .mockRejectedValueOnce(new Error('Async error'))
1028
+ *
1029
+ * await asyncMock() // first call
1030
+ * await asyncMock() // throws Error<'Async error'>
1031
+ */
1032
+ mockRejectedValueOnce(error: unknown): this;
1033
+ }
1034
+ type Mock<T extends Procedure | Constructable = Procedure> = MockInstance<T> & (T extends Constructable ? T extends Procedure ? {
1035
+ new (...args: ConstructorParameters<T>): InstanceType<T>;
1036
+ (...args: Parameters<T>): ReturnType<T>;
1037
+ } : {
1038
+ new (...args: ConstructorParameters<T>): InstanceType<T>;
1039
+ } : {
1040
+ new (...args: MockParameters<T>): MockReturnType<T>;
1041
+ (...args: MockParameters<T>): MockReturnType<T>;
1042
+ }) & { [P in keyof T]: T[P] };
1043
+ type PartialMaybePromise<T> = T extends Promise<Awaited<T>> ? Promise<Partial<Awaited<T>>> : Partial<T>;
1044
+ type PartialResultFunction<T> = T extends Constructable ? {
1045
+ new (...args: ConstructorParameters<T>): InstanceType<T>;
1046
+ } | {
1047
+ (this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
1048
+ } : T extends Procedure ? (...args: Parameters<T>) => PartialMaybePromise<ReturnType<T>> : T;
1049
+ type PartialMock<T extends Procedure | Constructable = Procedure> = Mock<PartialResultFunction<T extends Mock ? NonNullable<ReturnType<T["getMockImplementation"]>> : T>>;
1050
+ type DeepPartial<T> = T extends Procedure ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;
1051
+ type DeepPartialMaybePromise<T> = T extends Promise<Awaited<T>> ? Promise<DeepPartial<Awaited<T>>> : DeepPartial<T>;
1052
+ type DeepPartialResultFunction<T> = T extends Constructable ? {
1053
+ new (...args: ConstructorParameters<T>): InstanceType<T>;
1054
+ } | {
1055
+ (this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
1056
+ } : T extends Procedure ? (...args: Parameters<T>) => DeepPartialMaybePromise<ReturnType<T>> : T;
1057
+ type DeepPartialMock<T extends Procedure | Constructable = Procedure> = Mock<DeepPartialResultFunction<T extends Mock ? NonNullable<ReturnType<T["getMockImplementation"]>> : T>>;
1058
+ type MaybeMockedConstructor<T> = T extends Constructable ? Mock<T> : T;
1059
+ type MockedFunction<T extends Procedure | Constructable> = Mock<T> & MockedObject<T>;
1060
+ type PartiallyMockedFunction<T extends Procedure | Constructable> = PartialMock<T> & MockedObject<T>;
1061
+ type MockedFunctionDeep<T extends Procedure | Constructable> = Mock<T> & MockedObjectDeep<T>;
1062
+ type PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = DeepPartialMock<T> & MockedObjectDeep<T>;
1063
+ type MockedObject<T> = MaybeMockedConstructor<T> & { [K in Methods<T>]: T[K] extends Procedure ? MockedFunction<T[K]> : T[K] } & { [K in Properties<T>]: T[K] };
1064
+ type MockedObjectDeep<T> = MaybeMockedConstructor<T> & { [K in Methods<T>]: T[K] extends Procedure ? MockedFunctionDeep<T[K]> : T[K] } & { [K in Properties<T>]: MaybeMockedDeep<T[K]> };
1065
+ type MaybeMockedDeep<T> = T extends Procedure | Constructable ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
1066
+ type MaybePartiallyMockedDeep<T> = T extends Procedure | Constructable ? PartiallyMockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
1067
+ type MaybeMocked<T> = T extends Procedure | Constructable ? MockedFunction<T> : T extends object ? MockedObject<T> : T;
1068
+ type MaybePartiallyMocked<T> = T extends Procedure | Constructable ? PartiallyMockedFunction<T> : T extends object ? MockedObject<T> : T;
1069
+ interface Constructable {
1070
+ new (...args: any[]): any;
1071
+ }
1072
+ type MockedClass<T extends Constructable> = MockInstance<T> & {
1073
+ prototype: T extends {
1074
+ prototype: any;
1075
+ } ? Mocked<T["prototype"]> : never;
1076
+ } & T;
1077
+ type Mocked<T> = { [P in keyof T]: T[P] extends Procedure ? MockInstance<T[P]> : T[P] extends Constructable ? MockedClass<T[P]> : T[P] } & T;
1078
+ interface MockConfig {
1079
+ mockImplementation: Procedure | Constructable | undefined;
1080
+ mockOriginal: Procedure | Constructable | undefined;
1081
+ mockName: string;
1082
+ onceMockImplementations: Array<Procedure | Constructable>;
1083
+ }
1084
+ interface MockInstanceOption {
1085
+ originalImplementation?: Procedure | Constructable;
1086
+ mockImplementation?: Procedure | Constructable;
1087
+ resetToMockImplementation?: boolean;
1088
+ restore?: () => void;
1089
+ prototypeMembers?: (string | symbol)[];
1090
+ keepMembersImplementation?: boolean;
1091
+ prototypeState?: MockContext;
1092
+ prototypeConfig?: MockConfig;
1093
+ resetToMockName?: boolean;
1094
+ name?: string | symbol;
1095
+ }
1096
+
1097
+ declare function isMockFunction(fn: any): fn is Mock;
1098
+ declare function createMockInstance(options?: MockInstanceOption): Mock<Procedure | Constructable>;
1099
+ declare function fn<T extends Procedure | Constructable = Procedure>(originalImplementation?: T): Mock<T>;
1100
+ type SpyOnValue<
1101
+ T extends object,
1102
+ K extends keyof any
1103
+ > = K extends keyof Required<T> ? Required<T>[K] : (T & Record<K, unknown>)[K];
1104
+ type SpyOnMethod<
1105
+ T extends object,
1106
+ K extends keyof any
1107
+ > = SpyOnValue<T, K> extends Constructable | Procedure ? SpyOnValue<T, K> : never;
1108
+ type SpyOnMethodKey<
1109
+ T extends object,
1110
+ K extends keyof any
1111
+ > = SpyOnValue<T, K> extends Constructable | Procedure ? K : never;
1112
+ declare function spyOn<
1113
+ T extends object,
1114
+ S extends Properties<Required<T>>
1115
+ >(object: T, key: S, accessor: "get"): Mock<() => T[S]>;
1116
+ declare function spyOn<
1117
+ T extends object,
1118
+ G extends Properties<Required<T>>
1119
+ >(object: T, key: G, accessor: "set"): Mock<(arg: T[G]) => void>;
1120
+ declare function spyOn<
1121
+ T extends object,
1122
+ M extends Classes<Required<T>> | Methods<Required<T>>
1123
+ >(object: T, key: M): Required<T>[M] extends Constructable | Procedure ? Mock<Required<T>[M]> : never;
1124
+ declare function spyOn<
1125
+ T extends object,
1126
+ K extends keyof any
1127
+ >(object: T, key: SpyOnMethodKey<T, K>): Mock<SpyOnMethod<T, K>>;
1128
+ declare function restoreAllMocks(): void;
1129
+ declare function clearAllMocks(): void;
1130
+ declare function resetAllMocks(): void;
1131
+
1132
+ type _vitest_spy_Constructable = Constructable;
1133
+ type _vitest_spy_MaybeMocked<T> = MaybeMocked<T>;
1134
+ type _vitest_spy_MaybeMockedConstructor<T> = MaybeMockedConstructor<T>;
1135
+ type _vitest_spy_MaybeMockedDeep<T> = MaybeMockedDeep<T>;
1136
+ type _vitest_spy_MaybePartiallyMocked<T> = MaybePartiallyMocked<T>;
1137
+ type _vitest_spy_MaybePartiallyMockedDeep<T> = MaybePartiallyMockedDeep<T>;
1138
+ type _vitest_spy_Mock<T extends Procedure | Constructable = Procedure> = Mock<T>;
1139
+ type _vitest_spy_MockContext<T extends Procedure | Constructable = Procedure> = MockContext<T>;
1140
+ type _vitest_spy_MockInstance<T extends Procedure | Constructable = Procedure> = MockInstance<T>;
1141
+ type _vitest_spy_MockInstanceOption = MockInstanceOption;
1142
+ type _vitest_spy_MockParameters<T extends Procedure | Constructable> = MockParameters<T>;
1143
+ type _vitest_spy_MockProcedureContext<T extends Procedure | Constructable> = MockProcedureContext<T>;
1144
+ type _vitest_spy_MockResult<T> = MockResult<T>;
1145
+ type _vitest_spy_MockResultIncomplete = MockResultIncomplete;
1146
+ type _vitest_spy_MockResultReturn<T> = MockResultReturn<T>;
1147
+ type _vitest_spy_MockResultThrow = MockResultThrow;
1148
+ type _vitest_spy_MockReturnType<T extends Procedure | Constructable> = MockReturnType<T>;
1149
+ type _vitest_spy_MockSettledResult<T> = MockSettledResult<T>;
1150
+ type _vitest_spy_MockSettledResultFulfilled<T> = MockSettledResultFulfilled<T>;
1151
+ type _vitest_spy_MockSettledResultIncomplete = MockSettledResultIncomplete;
1152
+ type _vitest_spy_MockSettledResultRejected = MockSettledResultRejected;
1153
+ type _vitest_spy_Mocked<T> = Mocked<T>;
1154
+ type _vitest_spy_MockedClass<T extends Constructable> = MockedClass<T>;
1155
+ type _vitest_spy_MockedFunction<T extends Procedure | Constructable> = MockedFunction<T>;
1156
+ type _vitest_spy_MockedFunctionDeep<T extends Procedure | Constructable> = MockedFunctionDeep<T>;
1157
+ type _vitest_spy_MockedObject<T> = MockedObject<T>;
1158
+ type _vitest_spy_MockedObjectDeep<T> = MockedObjectDeep<T>;
1159
+ type _vitest_spy_PartialMock<T extends Procedure | Constructable = Procedure> = PartialMock<T>;
1160
+ type _vitest_spy_PartiallyMockedFunction<T extends Procedure | Constructable> = PartiallyMockedFunction<T>;
1161
+ type _vitest_spy_PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = PartiallyMockedFunctionDeep<T>;
1162
+ type _vitest_spy_Procedure = Procedure;
1163
+ declare const _vitest_spy_clearAllMocks: typeof clearAllMocks;
1164
+ declare const _vitest_spy_createMockInstance: typeof createMockInstance;
1165
+ declare const _vitest_spy_fn: typeof fn;
1166
+ declare const _vitest_spy_isMockFunction: typeof isMockFunction;
1167
+ declare const _vitest_spy_resetAllMocks: typeof resetAllMocks;
1168
+ declare const _vitest_spy_restoreAllMocks: typeof restoreAllMocks;
1169
+ declare const _vitest_spy_spyOn: typeof spyOn;
1170
+ declare namespace _vitest_spy {
1171
+ export { _vitest_spy_clearAllMocks as clearAllMocks, _vitest_spy_createMockInstance as createMockInstance, _vitest_spy_fn as fn, _vitest_spy_isMockFunction as isMockFunction, _vitest_spy_resetAllMocks as resetAllMocks, _vitest_spy_restoreAllMocks as restoreAllMocks, _vitest_spy_spyOn as spyOn };
1172
+ export type { _vitest_spy_Constructable as Constructable, _vitest_spy_MaybeMocked as MaybeMocked, _vitest_spy_MaybeMockedConstructor as MaybeMockedConstructor, _vitest_spy_MaybeMockedDeep as MaybeMockedDeep, _vitest_spy_MaybePartiallyMocked as MaybePartiallyMocked, _vitest_spy_MaybePartiallyMockedDeep as MaybePartiallyMockedDeep, _vitest_spy_Mock as Mock, _vitest_spy_MockContext as MockContext, _vitest_spy_MockInstance as MockInstance, _vitest_spy_MockInstanceOption as MockInstanceOption, _vitest_spy_MockParameters as MockParameters, _vitest_spy_MockProcedureContext as MockProcedureContext, _vitest_spy_MockResult as MockResult, _vitest_spy_MockResultIncomplete as MockResultIncomplete, _vitest_spy_MockResultReturn as MockResultReturn, _vitest_spy_MockResultThrow as MockResultThrow, _vitest_spy_MockReturnType as MockReturnType, _vitest_spy_MockSettledResult as MockSettledResult, _vitest_spy_MockSettledResultFulfilled as MockSettledResultFulfilled, _vitest_spy_MockSettledResultIncomplete as MockSettledResultIncomplete, _vitest_spy_MockSettledResultRejected as MockSettledResultRejected, _vitest_spy_Mocked as Mocked, _vitest_spy_MockedClass as MockedClass, _vitest_spy_MockedFunction as MockedFunction, _vitest_spy_MockedFunctionDeep as MockedFunctionDeep, _vitest_spy_MockedObject as MockedObject, _vitest_spy_MockedObjectDeep as MockedObjectDeep, _vitest_spy_PartialMock as PartialMock, _vitest_spy_PartiallyMockedFunction as PartiallyMockedFunction, _vitest_spy_PartiallyMockedFunctionDeep as PartiallyMockedFunctionDeep, _vitest_spy_Procedure as Procedure };
1173
+ }
1174
+
1175
+ interface Formatter {
1176
+ (input?: unknown): string;
1177
+ open: string;
1178
+ close: string;
1179
+ }
1180
+ declare function disableDefaultColors(): void;
1181
+
1182
+ interface AsymmetricMatcherInterface {
1183
+ asymmetricMatch: (other: unknown, customTesters?: Array<Tester>) => boolean;
1184
+ toString: () => string;
1185
+ getExpectedType?: () => string;
1186
+ toAsymmetricMatcher?: () => string;
1187
+ }
1188
+ declare abstract class AsymmetricMatcher<
1189
+ T,
1190
+ State extends MatcherState = MatcherState
1191
+ > implements AsymmetricMatcherInterface {
1192
+ protected sample: T;
1193
+ protected inverse: boolean;
1194
+ $$typeof: symbol;
1195
+ constructor(sample: T, inverse?: boolean);
1196
+ protected getMatcherContext(expect?: Chai.ExpectStatic): State;
1197
+ abstract asymmetricMatch(other: unknown, customTesters?: Array<Tester>): boolean;
1198
+ abstract toString(): string;
1199
+ getExpectedType?(): string;
1200
+ toAsymmetricMatcher?(): string;
1201
+ }
1202
+
1203
+ declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string;
1204
+ declare function printReceived(object: unknown): string;
1205
+ declare function printExpected(value: unknown): string;
1206
+ declare function getMatcherUtils(): {
1207
+ EXPECTED_COLOR: Formatter;
1208
+ RECEIVED_COLOR: Formatter;
1209
+ INVERTED_COLOR: Formatter;
1210
+ BOLD_WEIGHT: Formatter;
1211
+ DIM_COLOR: Formatter;
1212
+ diff: typeof diff;
1213
+ matcherHint: typeof matcherHint;
1214
+ printReceived: typeof printReceived;
1215
+ printExpected: typeof printExpected;
1216
+ printDiffOrStringify: typeof printDiffOrStringify;
1217
+ printWithType: typeof printWithType;
1218
+ };
1219
+ declare function printWithType<T>(name: string, value: T, print: (value: T) => string): string;
1220
+ type Tester = (this: TesterContext, a: any, b: any, customTesters: Array<Tester>) => boolean | undefined;
1221
+ interface TesterContext {
1222
+ equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
1223
+ }
1224
+
1225
+ interface MatcherHintOptions {
1226
+ comment?: string;
1227
+ expectedColor?: Formatter;
1228
+ isDirectExpectCall?: boolean;
1229
+ isNot?: boolean;
1230
+ promise?: string;
1231
+ receivedColor?: Formatter;
1232
+ secondArgument?: string;
1233
+ secondArgumentColor?: Formatter;
1234
+ }
1235
+ interface MatcherState {
1236
+ customTesters: Array<Tester>;
1237
+ assertionCalls: number;
1238
+ currentTestName?: string;
1239
+ /**
1240
+ * @deprecated exists only in types
1241
+ */
1242
+ dontThrow?: () => void;
1243
+ /**
1244
+ * @deprecated exists only in types
1245
+ */
1246
+ error?: Error;
1247
+ equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
1248
+ /**
1249
+ * @deprecated exists only in types
1250
+ */
1251
+ expand?: boolean;
1252
+ expectedAssertionsNumber?: number | null;
1253
+ expectedAssertionsNumberErrorGen?: (() => Error) | null;
1254
+ isExpectingAssertions?: boolean;
1255
+ isExpectingAssertionsError?: Error | null;
1256
+ isNot: boolean;
1257
+ promise: string;
1258
+ /**
1259
+ * @deprecated exists only in types
1260
+ */
1261
+ suppressedErrors: Array<Error>;
1262
+ testPath?: string;
1263
+ utils: ReturnType<typeof getMatcherUtils> & {
1264
+ diff: typeof diff;
1265
+ stringify: typeof stringify;
1266
+ iterableEquality: Tester;
1267
+ subsetEquality: Tester;
1268
+ };
1269
+ soft?: boolean;
1270
+ poll?: boolean;
1271
+ /**
1272
+ * The same assertion instance that chai plugins receive.
1273
+ * @experimental
1274
+ * @see {@link https://www.chaijs.com/guide/plugins/} Core Plugin Concepts
1275
+ */
1276
+ readonly assertion: Assertion;
1277
+ }
1278
+ interface SyncExpectationResult {
1279
+ pass: boolean;
1280
+ message: () => string;
1281
+ actual?: any;
1282
+ expected?: any;
1283
+ meta?: object;
1284
+ }
1285
+ type AsyncExpectationResult = Promise<SyncExpectationResult>;
1286
+ type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
1287
+ interface RawMatcherFn<
1288
+ T extends MatcherState = MatcherState,
1289
+ E extends Array<any> = Array<any>
1290
+ > {
1291
+ (this: T, received: any, ...expected: E): ExpectationResult;
1292
+ }
1293
+ interface Matchers<
1294
+ R extends void | Promise<void> = void | Promise<void>,
1295
+ T = unknown
1296
+ > {}
1297
+ type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>> & ThisType<T> & { [K in keyof Matchers]?: RawMatcherFn<T, Parameters<Matchers[K]>> };
1298
+ interface ExpectStatic extends Chai.ExpectStatic, Matchers<any>, AsymmetricMatchersContaining {
1299
+ <T>(actual: T, message?: string): Assertion<void, T>;
1300
+ extend: (expects: MatchersObject) => void;
1301
+ anything: () => any;
1302
+ any: (constructor: unknown) => any;
1303
+ getState: () => MatcherState;
1304
+ setState: (state: Partial<MatcherState>) => void;
1305
+ not: AsymmetricMatchersContaining;
1306
+ }
1307
+ interface CustomMatcher<R = any> {
1308
+ /**
1309
+ * Checks that a value satisfies a custom matcher function.
1310
+ *
1311
+ * @param matcher - A function returning a boolean based on the custom condition
1312
+ * @param message - Optional custom error message on failure
1313
+ *
1314
+ * @example
1315
+ * expect(age).toSatisfy(val => val >= 18, 'Age must be at least 18');
1316
+ * expect(age).toEqual(expect.toSatisfy(val => val >= 18, 'Age must be at least 18'));
1317
+ */
1318
+ toSatisfy: (matcher: (value: any) => boolean, message?: string) => R;
1319
+ /**
1320
+ * Matches if the received value is one of the values in the expected array or set.
1321
+ *
1322
+ * @example
1323
+ * expect(1).toBeOneOf([1, 2, 3])
1324
+ * expect('foo').toBeOneOf([expect.any(String)])
1325
+ * expect({ a: 1 }).toEqual({ a: expect.toBeOneOf(['1', '2', '3']) })
1326
+ */
1327
+ toBeOneOf: <T>(sample: ReadonlyArray<T> | ReadonlySet<T>) => R;
1328
+ }
1329
+ interface AsymmetricMatchersContaining extends Matchers<any>, CustomMatcher {
1330
+ /**
1331
+ * Matches if the received string contains the expected substring.
1332
+ *
1333
+ * @example
1334
+ * expect('I have an apple').toEqual(expect.stringContaining('apple'));
1335
+ * expect({ a: 'test string' }).toEqual({ a: expect.stringContaining('test') });
1336
+ */
1337
+ stringContaining: (expected: string) => any;
1338
+ /**
1339
+ * Matches if the received object contains all properties of the expected object.
1340
+ *
1341
+ * @example
1342
+ * expect({ a: '1', b: 2 }).toEqual(expect.objectContaining({ a: '1' }))
1343
+ */
1344
+ objectContaining: <T = any>(expected: DeeplyAllowMatchers<T>) => any;
1345
+ /**
1346
+ * Matches if the received array contains all elements in the expected array.
1347
+ *
1348
+ * @example
1349
+ * expect(['a', 'b', 'c']).toEqual(expect.arrayContaining(['b', 'a']));
1350
+ */
1351
+ arrayContaining: <T = unknown>(expected: Array<DeeplyAllowMatchers<T>>) => any;
1352
+ /**
1353
+ * Matches if the received string or regex matches the expected pattern.
1354
+ *
1355
+ * @example
1356
+ * expect('hello world').toEqual(expect.stringMatching(/^hello/));
1357
+ * expect('hello world').toEqual(expect.stringMatching('hello'));
1358
+ */
1359
+ stringMatching: (expected: string | RegExp) => any;
1360
+ /**
1361
+ * Matches if the received number is within a certain precision of the expected number.
1362
+ *
1363
+ * @example
1364
+ * expect(10.45).toEqual(expect.closeTo(10.5, 1));
1365
+ * expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision
1366
+ */
1367
+ closeTo: (expected: number, precision?: number) => any;
1368
+ /**
1369
+ * Matches if the received value validates against a Standard Schema.
1370
+ *
1371
+ * @param schema - A Standard Schema V1 compatible schema object
1372
+ *
1373
+ * @example
1374
+ * expect(user).toEqual(expect.schemaMatching(z.object({ name: z.string() })))
1375
+ * expect(['hello', 'world']).toEqual([expect.schemaMatching(z.string()), expect.schemaMatching(z.string())])
1376
+ */
1377
+ schemaMatching: (schema: unknown) => any;
1378
+ }
1379
+ type WithAsymmetricMatcher<T> = T | AsymmetricMatcher<unknown>;
1380
+ 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>;
1381
+ interface JestAssertion<
1382
+ R extends void | Promise<void>,
1383
+ T = unknown
1384
+ > extends CustomMatcher<R> {
1385
+ /**
1386
+ * Used when you want to check that two objects have the same value.
1387
+ * This matcher recursively checks the equality of all fields, rather than checking for object identity.
1388
+ *
1389
+ * @example
1390
+ * expect(user).toEqual({ name: 'Alice', age: 30 });
1391
+ */
1392
+ toEqual: <E>(expected: E) => R;
1393
+ /**
1394
+ * Use to test that objects have the same types as well as structure.
1395
+ *
1396
+ * @example
1397
+ * expect(user).toStrictEqual({ name: 'Alice', age: 30 });
1398
+ */
1399
+ toStrictEqual: <E>(expected: E) => R;
1400
+ /**
1401
+ * Checks that a value is what you expect. It calls `Object.is` to compare values.
1402
+ * Don't use `toBe` with floating-point numbers.
1403
+ *
1404
+ * @example
1405
+ * expect(result).toBe(42);
1406
+ * expect(status).toBe(true);
1407
+ */
1408
+ toBe: <E>(expected: E) => R;
1409
+ /**
1410
+ * Check that a string matches a regular expression.
1411
+ *
1412
+ * @example
1413
+ * expect(message).toMatch(/hello/);
1414
+ * expect(greeting).toMatch('world');
1415
+ */
1416
+ toMatch: (expected: string | RegExp) => R;
1417
+ /**
1418
+ * Used to check that a JavaScript object matches a subset of the properties of an object
1419
+ *
1420
+ * @example
1421
+ * expect(user).toMatchObject({
1422
+ * name: 'Alice',
1423
+ * address: { city: 'Wonderland' }
1424
+ * });
1425
+ */
1426
+ toMatchObject: <E extends object | any[]>(expected: E) => R;
1427
+ /**
1428
+ * Used when you want to check that an item is in a list.
1429
+ * For testing the items in the list, this uses `===`, a strict equality check.
1430
+ *
1431
+ * @example
1432
+ * expect(items).toContain('apple');
1433
+ * expect(numbers).toContain(5);
1434
+ */
1435
+ toContain: <E>(item: E) => R;
1436
+ /**
1437
+ * Used when you want to check that an item is in a list.
1438
+ * For testing the items in the list, this matcher recursively checks the
1439
+ * equality of all fields, rather than checking for object identity.
1440
+ *
1441
+ * @example
1442
+ * expect(items).toContainEqual({ name: 'apple', quantity: 1 });
1443
+ */
1444
+ toContainEqual: <E>(item: E) => R;
1445
+ /**
1446
+ * Use when you don't care what a value is, you just want to ensure a value
1447
+ * is true in a boolean context. In JavaScript, there are six falsy values:
1448
+ * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy.
1449
+ *
1450
+ * @example
1451
+ * expect(user.isActive).toBeTruthy();
1452
+ */
1453
+ toBeTruthy: () => R;
1454
+ /**
1455
+ * When you don't care what a value is, you just want to
1456
+ * ensure a value is false in a boolean context.
1457
+ *
1458
+ * @example
1459
+ * expect(user.isActive).toBeFalsy();
1460
+ */
1461
+ toBeFalsy: () => R;
1462
+ /**
1463
+ * For comparing floating point numbers.
1464
+ *
1465
+ * @example
1466
+ * expect(score).toBeGreaterThan(10);
1467
+ */
1468
+ toBeGreaterThan: (num: number | bigint) => R;
1469
+ /**
1470
+ * For comparing floating point numbers.
1471
+ *
1472
+ * @example
1473
+ * expect(score).toBeGreaterThanOrEqual(10);
1474
+ */
1475
+ toBeGreaterThanOrEqual: (num: number | bigint) => R;
1476
+ /**
1477
+ * For comparing floating point numbers.
1478
+ *
1479
+ * @example
1480
+ * expect(score).toBeLessThan(10);
1481
+ */
1482
+ toBeLessThan: (num: number | bigint) => R;
1483
+ /**
1484
+ * For comparing floating point numbers.
1485
+ *
1486
+ * @example
1487
+ * expect(score).toBeLessThanOrEqual(10);
1488
+ */
1489
+ toBeLessThanOrEqual: (num: number | bigint) => R;
1490
+ /**
1491
+ * Used to check that a variable is NaN.
1492
+ *
1493
+ * @example
1494
+ * expect(value).toBeNaN();
1495
+ */
1496
+ toBeNaN: () => R;
1497
+ /**
1498
+ * Used to check that a variable is undefined.
1499
+ *
1500
+ * @example
1501
+ * expect(value).toBeUndefined();
1502
+ */
1503
+ toBeUndefined: () => R;
1504
+ /**
1505
+ * This is the same as `.toBe(null)` but the error messages are a bit nicer.
1506
+ * So use `.toBeNull()` when you want to check that something is null.
1507
+ *
1508
+ * @example
1509
+ * expect(value).toBeNull();
1510
+ */
1511
+ toBeNull: () => R;
1512
+ /**
1513
+ * Used to check that a variable is nullable (null or undefined).
1514
+ *
1515
+ * @example
1516
+ * expect(value).toBeNullable();
1517
+ */
1518
+ toBeNullable: () => R;
1519
+ /**
1520
+ * Ensure that a variable is not undefined.
1521
+ *
1522
+ * @example
1523
+ * expect(value).toBeDefined();
1524
+ */
1525
+ toBeDefined: () => R;
1526
+ /**
1527
+ * Ensure that an object is an instance of a class.
1528
+ * This matcher uses `instanceof` underneath.
1529
+ *
1530
+ * @example
1531
+ * expect(new Date()).toBeInstanceOf(Date);
1532
+ */
1533
+ toBeInstanceOf: <E>(expected: E) => R;
1534
+ /**
1535
+ * Used to check that an object has a `.length` property
1536
+ * and it is set to a certain numeric value.
1537
+ *
1538
+ * @example
1539
+ * expect([1, 2, 3]).toHaveLength(3);
1540
+ * expect('hello').toHaveLength(5);
1541
+ */
1542
+ toHaveLength: (length: number) => R;
1543
+ /**
1544
+ * Use to check if a property at the specified path exists on an object.
1545
+ * For checking deeply nested properties, you may use dot notation or an array containing
1546
+ * the path segments for deep references.
1547
+ *
1548
+ * Optionally, you can provide a value to check if it matches the value present at the path
1549
+ * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks
1550
+ * the equality of all fields.
1551
+ *
1552
+ * @example
1553
+ * expect(user).toHaveProperty('address.city', 'New York');
1554
+ * expect(config).toHaveProperty(['settings', 'theme'], 'dark');
1555
+ */
1556
+ toHaveProperty: <E>(property: string | (string | number)[], value?: E) => R;
1557
+ /**
1558
+ * Using exact equality with floating point numbers is a bad idea.
1559
+ * Rounding means that intuitive things fail.
1560
+ * The default for `numDigits` is 2.
1561
+ *
1562
+ * @example
1563
+ * expect(price).toBeCloseTo(9.99, 2);
1564
+ */
1565
+ toBeCloseTo: (number: number, numDigits?: number) => R;
1566
+ /**
1567
+ * Ensures that a mock function is called an exact number of times.
1568
+ *
1569
+ * Also under the alias `expect.toBeCalledTimes`.
1570
+ *
1571
+ * @example
1572
+ * expect(mockFunc).toHaveBeenCalledTimes(2);
1573
+ */
1574
+ toHaveBeenCalledTimes: (times: number) => R;
1575
+ /**
1576
+ * Ensures that a mock function is called an exact number of times.
1577
+ *
1578
+ * Alias for `expect.toHaveBeenCalledTimes`.
1579
+ *
1580
+ * @example
1581
+ * expect(mockFunc).toBeCalledTimes(2);
1582
+ * @deprecated Use `toHaveBeenCalledTimes` instead
1583
+ */
1584
+ toBeCalledTimes: (times: number) => R;
1585
+ /**
1586
+ * Ensures that a mock function is called.
1587
+ *
1588
+ * Also under the alias `expect.toBeCalled`.
1589
+ *
1590
+ * @example
1591
+ * expect(mockFunc).toHaveBeenCalled();
1592
+ */
1593
+ toHaveBeenCalled: () => R;
1594
+ /**
1595
+ * Ensures that a mock function is called.
1596
+ *
1597
+ * Alias for `expect.toHaveBeenCalled`.
1598
+ *
1599
+ * @example
1600
+ * expect(mockFunc).toBeCalled();
1601
+ * @deprecated Use `toHaveBeenCalled` instead
1602
+ */
1603
+ toBeCalled: () => R;
1604
+ /**
1605
+ * Ensure that a mock function is called with specific arguments.
1606
+ *
1607
+ * Also under the alias `expect.toBeCalledWith`.
1608
+ *
1609
+ * @example
1610
+ * expect(mockFunc).toHaveBeenCalledWith('arg1', 42);
1611
+ */
1612
+ toHaveBeenCalledWith: <E extends any[]>(...args: E) => R;
1613
+ /**
1614
+ * Ensure that a mock function is called with specific arguments.
1615
+ *
1616
+ * Alias for `expect.toHaveBeenCalledWith`.
1617
+ *
1618
+ * @example
1619
+ * expect(mockFunc).toBeCalledWith('arg1', 42);
1620
+ * @deprecated Use `toHaveBeenCalledWith` instead
1621
+ */
1622
+ toBeCalledWith: <E extends any[]>(...args: E) => R;
1623
+ /**
1624
+ * Ensure that a mock function is called with specific arguments on an Nth call.
1625
+ *
1626
+ * Also under the alias `expect.nthCalledWith`.
1627
+ *
1628
+ * @example
1629
+ * expect(mockFunc).toHaveBeenNthCalledWith(2, 'secondArg');
1630
+ */
1631
+ toHaveBeenNthCalledWith: <E extends any[]>(n: number, ...args: E) => R;
1632
+ /**
1633
+ * If you have a mock function, you can use `.toHaveBeenLastCalledWith`
1634
+ * to test what arguments it was last called with.
1635
+ *
1636
+ * Also under the alias `expect.lastCalledWith`.
1637
+ *
1638
+ * @example
1639
+ * expect(mockFunc).toHaveBeenLastCalledWith('lastArg');
1640
+ */
1641
+ toHaveBeenLastCalledWith: <E extends any[]>(...args: E) => R;
1642
+ /**
1643
+ * Used to test that a function throws when it is called.
1644
+ *
1645
+ * Also under the alias `expect.toThrowError`.
1646
+ *
1647
+ * @example
1648
+ * expect(() => functionWithError()).toThrow('Error message');
1649
+ * expect(() => parseJSON('invalid')).toThrow(SyntaxError);
1650
+ * expect(() => { throw 42 }).toThrow(42);
1651
+ */
1652
+ toThrow: (expected?: any) => R;
1653
+ /**
1654
+ * Used to test that a function throws when it is called.
1655
+ *
1656
+ * Alias for `expect.toThrow`.
1657
+ *
1658
+ * @example
1659
+ * expect(() => functionWithError()).toThrowError('Error message');
1660
+ * expect(() => parseJSON('invalid')).toThrowError(SyntaxError);
1661
+ * expect(() => { throw 42 }).toThrowError(42);
1662
+ * @deprecated Use `toThrow` instead
1663
+ */
1664
+ toThrowError: (expected?: any) => R;
1665
+ /**
1666
+ * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
1667
+ *
1668
+ * Alias for `expect.toHaveReturned`.
1669
+ *
1670
+ * @example
1671
+ * expect(mockFunc).toReturn();
1672
+ * @deprecated Use `toHaveReturned` instead
1673
+ */
1674
+ toReturn: () => R;
1675
+ /**
1676
+ * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
1677
+ *
1678
+ * Also under the alias `expect.toReturn`.
1679
+ *
1680
+ * @example
1681
+ * expect(mockFunc).toHaveReturned();
1682
+ */
1683
+ toHaveReturned: () => R;
1684
+ /**
1685
+ * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
1686
+ * Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
1687
+ *
1688
+ * Alias for `expect.toHaveReturnedTimes`.
1689
+ *
1690
+ * @example
1691
+ * expect(mockFunc).toReturnTimes(3);
1692
+ * @deprecated Use `toHaveReturnedTimes` instead
1693
+ */
1694
+ toReturnTimes: (times: number) => R;
1695
+ /**
1696
+ * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
1697
+ * Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
1698
+ *
1699
+ * Also under the alias `expect.toReturnTimes`.
1700
+ *
1701
+ * @example
1702
+ * expect(mockFunc).toHaveReturnedTimes(3);
1703
+ */
1704
+ toHaveReturnedTimes: (times: number) => R;
1705
+ /**
1706
+ * Use to ensure that a mock function returned a specific value.
1707
+ *
1708
+ * Alias for `expect.toHaveReturnedWith`.
1709
+ *
1710
+ * @example
1711
+ * expect(mockFunc).toReturnWith('returnValue');
1712
+ * @deprecated Use `toHaveReturnedWith` instead
1713
+ */
1714
+ toReturnWith: <E>(value: E) => R;
1715
+ /**
1716
+ * Use to ensure that a mock function returned a specific value.
1717
+ *
1718
+ * Also under the alias `expect.toReturnWith`.
1719
+ *
1720
+ * @example
1721
+ * expect(mockFunc).toHaveReturnedWith('returnValue');
1722
+ */
1723
+ toHaveReturnedWith: <E>(value: E) => R;
1724
+ /**
1725
+ * Use to test the specific value that a mock function last returned.
1726
+ * If the last call to the mock function threw an error, then this matcher will fail
1727
+ * no matter what value you provided as the expected return value.
1728
+ *
1729
+ * Also under the alias `expect.lastReturnedWith`.
1730
+ *
1731
+ * @example
1732
+ * expect(mockFunc).toHaveLastReturnedWith('lastValue');
1733
+ */
1734
+ toHaveLastReturnedWith: <E>(value: E) => R;
1735
+ /**
1736
+ * Use to test the specific value that a mock function returned for the nth call.
1737
+ * If the nth call to the mock function threw an error, then this matcher will fail
1738
+ * no matter what value you provided as the expected return value.
1739
+ *
1740
+ * Also under the alias `expect.nthReturnedWith`.
1741
+ *
1742
+ * @example
1743
+ * expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue');
1744
+ */
1745
+ toHaveNthReturnedWith: <E>(nthCall: number, value: E) => R;
1746
+ }
1747
+ type VitestAssertion<
1748
+ A,
1749
+ R extends void | Promise<void>,
1750
+ T = unknown
1751
+ > = { [K in keyof A]: A[K] extends Chai.Assertion ? Assertion<R, T> : A[K] extends (...args: any[]) => any ? R extends Promise<void> ? PromisifyFunction<A[K]> : A[K] : VitestAssertion<A[K], R, T> } & ((type: string, message?: string) => Assertion<R, T>);
1752
+ type Promisify<O> = { [K in keyof O]: PromisifyFunction<O[K]> };
1753
+ type PromisifyFunction<T> = T extends (...args: infer A) => infer R ? Promisify<T> & ((...args: A) => R extends Promise<any> ? R : Promise<R>) : T;
1754
+ type PromisifyAssertion<T> = Assertion<Promise<void>, Awaited<T>>;
1755
+ interface Assertion<
1756
+ R extends void | Promise<void> = void,
1757
+ T = unknown
1758
+ > extends VitestAssertion<Chai.Assertion, R, T>, JestAssertion<R, T>, ChaiMockAssertion<R, T>, Matchers<R, T> {
1759
+ /**
1760
+ * Ensures a value is of a specific type.
1761
+ *
1762
+ * @example
1763
+ * expect(value).toBeTypeOf('string');
1764
+ * expect(number).toBeTypeOf('number');
1765
+ */
1766
+ toBeTypeOf: (expected: "bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol" | "undefined") => R;
1767
+ /**
1768
+ * Asserts that a mock function was called exactly once.
1769
+ *
1770
+ * @example
1771
+ * expect(mockFunc).toHaveBeenCalledOnce();
1772
+ */
1773
+ toHaveBeenCalledOnce: () => R;
1774
+ /**
1775
+ * Ensure that a mock function is called with specific arguments and called
1776
+ * exactly once.
1777
+ *
1778
+ * @example
1779
+ * expect(mockFunc).toHaveBeenCalledExactlyOnceWith('arg1', 42);
1780
+ */
1781
+ toHaveBeenCalledExactlyOnceWith: <E extends any[]>(...args: E) => R;
1782
+ /**
1783
+ * This assertion checks if a `Mock` was called before another `Mock`.
1784
+ * @param mock - A mock function created by `vi.spyOn` or `vi.fn`
1785
+ * @param failIfNoFirstInvocation - Fail if the first mock was never called
1786
+ * @example
1787
+ * const mock1 = vi.fn()
1788
+ * const mock2 = vi.fn()
1789
+ *
1790
+ * mock1()
1791
+ * mock2()
1792
+ * mock1()
1793
+ *
1794
+ * expect(mock1).toHaveBeenCalledBefore(mock2)
1795
+ */
1796
+ toHaveBeenCalledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => R;
1797
+ /**
1798
+ * This assertion checks if a `Mock` was called after another `Mock`.
1799
+ * @param mock - A mock function created by `vi.spyOn` or `vi.fn`
1800
+ * @param failIfNoFirstInvocation - Fail if the first mock was never called
1801
+ * @example
1802
+ * const mock1 = vi.fn()
1803
+ * const mock2 = vi.fn()
1804
+ *
1805
+ * mock2()
1806
+ * mock1()
1807
+ * mock2()
1808
+ *
1809
+ * expect(mock1).toHaveBeenCalledAfter(mock2)
1810
+ */
1811
+ toHaveBeenCalledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => R;
1812
+ /**
1813
+ * Checks that at least one of the mock function's calls has resolved.
1814
+ *
1815
+ * @example
1816
+ * expect(mockAsyncFunc).toHaveResolved();
1817
+ */
1818
+ toHaveResolved: () => R;
1819
+ /**
1820
+ * Checks that at least one of the mock function's calls has resolved to a specific value.
1821
+ *
1822
+ * @example
1823
+ * expect(mockAsyncFunc).toHaveResolvedWith('success');
1824
+ */
1825
+ toHaveResolvedWith: <E>(value: E) => R;
1826
+ /**
1827
+ * Ensures a promise resolves a specific number of times.
1828
+ *
1829
+ * @example
1830
+ * expect(mockAsyncFunc).toHaveResolvedTimes(3);
1831
+ */
1832
+ toHaveResolvedTimes: (times: number) => R;
1833
+ /**
1834
+ * Asserts that the last resolved value of a promise matches an expected value.
1835
+ *
1836
+ * @example
1837
+ * await expect(mockAsyncFunc).toHaveLastResolvedWith('finalResult');
1838
+ */
1839
+ toHaveLastResolvedWith: <E>(value: E) => R;
1840
+ /**
1841
+ * Ensures a specific value was returned by a promise on the nth resolution.
1842
+ *
1843
+ * @example
1844
+ * await expect(mockAsyncFunc).toHaveNthResolvedWith(2, 'secondResult');
1845
+ */
1846
+ toHaveNthResolvedWith: <E>(nthCall: number, value: E) => R;
1847
+ /**
1848
+ * Verifies that a promise resolves.
1849
+ *
1850
+ * @example
1851
+ * await expect(someAsyncFunc).resolves.toBe(42);
1852
+ */
1853
+ resolves: PromisifyAssertion<T>;
1854
+ /**
1855
+ * Verifies that a promise rejects.
1856
+ *
1857
+ * @example
1858
+ * await expect(someAsyncFunc).rejects.toThrow('error');
1859
+ */
1860
+ rejects: PromisifyAssertion<unknown>;
1861
+ }
1862
+ /**
1863
+ * Chai-style assertions for spy/mock testing.
1864
+ * These provide sinon-chai compatible assertion names that delegate to Jest-style implementations.
1865
+ */
1866
+ interface ChaiMockAssertion<
1867
+ R extends void | Promise<void>,
1868
+ T = unknown
1869
+ > {
1870
+ /**
1871
+ * Checks that a spy was called at least once.
1872
+ * Chai-style equivalent of `toHaveBeenCalled`.
1873
+ *
1874
+ * @example
1875
+ * expect(spy).to.have.been.called
1876
+ */
1877
+ readonly called: Assertion<R, T>;
1878
+ /**
1879
+ * Checks that a spy was called a specific number of times.
1880
+ * Chai-style equivalent of `toHaveBeenCalledTimes`.
1881
+ *
1882
+ * @example
1883
+ * expect(spy).to.have.callCount(3)
1884
+ */
1885
+ callCount: (count: number) => R;
1886
+ /**
1887
+ * Checks that a spy was called with specific arguments at least once.
1888
+ * Chai-style equivalent of `toHaveBeenCalledWith`.
1889
+ *
1890
+ * @example
1891
+ * expect(spy).to.have.been.calledWith('arg1', 'arg2')
1892
+ */
1893
+ calledWith: <E extends any[]>(...args: E) => R;
1894
+ /**
1895
+ * Checks that a spy was called exactly once.
1896
+ * Chai-style equivalent of `toHaveBeenCalledOnce`.
1897
+ *
1898
+ * @example
1899
+ * expect(spy).to.have.been.calledOnce
1900
+ */
1901
+ readonly calledOnce: Assertion<R, T>;
1902
+ /**
1903
+ * Checks that a spy was called exactly once with specific arguments.
1904
+ * Chai-style equivalent of `toHaveBeenCalledExactlyOnceWith`.
1905
+ *
1906
+ * @example
1907
+ * expect(spy).to.have.been.calledOnceWith('arg1', 'arg2')
1908
+ */
1909
+ calledOnceWith: <E extends any[]>(...args: E) => R;
1910
+ /**
1911
+ * Checks that the last call to a spy was made with specific arguments.
1912
+ * Chai-style equivalent of `toHaveBeenLastCalledWith`.
1913
+ *
1914
+ * @example
1915
+ * expect(spy).to.have.been.lastCalledWith('arg1', 'arg2')
1916
+ */
1917
+ lastCalledWith: <E extends any[]>(...args: E) => R;
1918
+ /**
1919
+ * Checks that the nth call to a spy was made with specific arguments.
1920
+ * Chai-style equivalent of `toHaveBeenNthCalledWith`.
1921
+ *
1922
+ * @example
1923
+ * expect(spy).to.have.been.nthCalledWith(2, 'arg1', 'arg2')
1924
+ */
1925
+ nthCalledWith: <E extends any[]>(n: number, ...args: E) => R;
1926
+ /**
1927
+ * Checks that a spy returned a specific value at least once.
1928
+ * Chai-style equivalent of `toHaveReturnedWith`.
1929
+ *
1930
+ * @example
1931
+ * expect(spy).to.have.returned('value')
1932
+ */
1933
+ returned: <E>(value: E) => R;
1934
+ /**
1935
+ * Checks that a spy returned a specific value at least once.
1936
+ * Chai-style equivalent of `toHaveReturnedWith`.
1937
+ *
1938
+ * @example
1939
+ * expect(spy).to.have.returnedWith('value')
1940
+ */
1941
+ returnedWith: <E>(value: E) => R;
1942
+ /**
1943
+ * Checks that a spy returned successfully a specific number of times.
1944
+ * Chai-style equivalent of `toHaveReturnedTimes`.
1945
+ *
1946
+ * @example
1947
+ * expect(spy).to.have.returnedTimes(3)
1948
+ */
1949
+ returnedTimes: (count: number) => R;
1950
+ /**
1951
+ * Checks that the last return value of a spy matches the expected value.
1952
+ * Chai-style equivalent of `toHaveLastReturnedWith`.
1953
+ *
1954
+ * @example
1955
+ * expect(spy).to.have.lastReturnedWith('value')
1956
+ */
1957
+ lastReturnedWith: <E>(value: E) => R;
1958
+ /**
1959
+ * Checks that the nth return value of a spy matches the expected value.
1960
+ * Chai-style equivalent of `toHaveNthReturnedWith`.
1961
+ *
1962
+ * @example
1963
+ * expect(spy).to.have.nthReturnedWith(2, 'value')
1964
+ */
1965
+ nthReturnedWith: <E>(n: number, value: E) => R;
1966
+ /**
1967
+ * Checks that a spy was called before another spy.
1968
+ * Chai-style equivalent of `toHaveBeenCalledBefore`.
1969
+ *
1970
+ * @example
1971
+ * expect(spy1).to.have.been.calledBefore(spy2)
1972
+ */
1973
+ calledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => R;
1974
+ /**
1975
+ * Checks that a spy was called after another spy.
1976
+ * Chai-style equivalent of `toHaveBeenCalledAfter`.
1977
+ *
1978
+ * @example
1979
+ * expect(spy1).to.have.been.calledAfter(spy2)
1980
+ */
1981
+ calledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => R;
1982
+ /**
1983
+ * Checks that a spy was called exactly twice.
1984
+ * Chai-style equivalent of `toHaveBeenCalledTimes(2)`.
1985
+ *
1986
+ * @example
1987
+ * expect(spy).to.have.been.calledTwice
1988
+ */
1989
+ readonly calledTwice: Assertion<R, T>;
1990
+ /**
1991
+ * Checks that a spy was called exactly three times.
1992
+ * Chai-style equivalent of `toHaveBeenCalledTimes(3)`.
1993
+ *
1994
+ * @example
1995
+ * expect(spy).to.have.been.calledThrice
1996
+ */
1997
+ readonly calledThrice: Assertion<R, T>;
1998
+ }
1999
+
2000
+ type ExtractBenchNames<T extends BenchRegistration<any>[]> = Exclude<{ [K in keyof T]: T[K] extends BenchRegistration<infer N> ? N : never }[number], never>;
2001
+ /**
2002
+ * A benchmarked function. Vitest-owned and engine-agnostic.
2003
+ */
2004
+ type BenchFn = Fn;
2005
+ /**
2006
+ * Per-benchmark initialization options passed to `bench(name, options, fn)`.
2007
+ */
2008
+ type BenchOptions = FnOptions;
2009
+ /**
2010
+ * Engine-neutral run options forwarded to a {@link BenchmarkProvider}. These
2011
+ * come from the optional trailing options argument of `bench.compare()` and
2012
+ * `registration.run()`.
2013
+ */
2014
+ type BenchRunOptions = BenchOptions$1;
2015
+ /**
2016
+ * The result of a single benchmark, produced by a {@link BenchmarkProvider}.
2017
+ * Structurally compatible with tinybench's task statistics so it flows
2018
+ * unchanged into the reporter, `bench.from()` baselines and comparison tables.
2019
+ * The `name` matches the corresponding {@link BenchRegistration}.
2020
+ */
2021
+ interface BenchResult extends TaskResultCompleted, TaskResultRuntimeInfo, TaskResultTimestampProviderInfo {
2022
+ /** The registered benchmark name this result belongs to. */
2023
+ name: string;
2024
+ }
2025
+ /**
2026
+ * A benchmark defined by `bench()` (or `bench.from()`), as seen by a
2027
+ * {@link BenchmarkProvider}. `fn`/`fnOpts` are absent for `bench.from()`
2028
+ * registrations, which are resolved from a stored baseline instead of run.
2029
+ */
2030
+ interface BenchRegistrationInput {
2031
+ name: string;
2032
+ fn: BenchFn;
2033
+ fnOpts?: BenchOptions;
2034
+ }
2035
+ /**
2036
+ * The set of benchmarks registered by a single test, handed to
2037
+ * {@link BenchmarkProvider.run}.
2038
+ */
2039
+ interface BenchmarkGroup {
2040
+ /** The test that registered these benchmarks. */
2041
+ test: Test;
2042
+ /** The resolved benchmark configuration for the current project. */
2043
+ config: SerializedConfig["benchmark"];
2044
+ /** The runnable registrations, in registration order. */
2045
+ registrations: BenchRegistrationInput[];
2046
+ /** Engine-neutral run options, when provided by the caller. */
2047
+ options?: BenchRunOptions;
2048
+ }
2049
+ /**
2050
+ * Executes the benchmarks of a single test and returns their results.
2051
+ *
2052
+ * A custom provider module must default-export an object of this shape.
2053
+ *
2054
+ * The returned array is the sole source of results: it's what `bench().run()`
2055
+ * resolves to and what the reporter serializes. Results are matched to
2056
+ * registrations by `name`; return one {@link BenchResult} per registration.
2057
+ *
2058
+ * @experimental
2059
+ */
2060
+ interface BenchmarkProvider {
2061
+ run: (group: BenchmarkGroup) => Promise<BenchResult[]>;
2062
+ }
2063
+ interface BenchStorage<T extends string> {
2064
+ get: (name: T) => BenchResult;
2065
+ }
2066
+
2067
+ /**
2068
+ * Options accepted by `bench(name, options, fn)`. Extends the per-benchmark
2069
+ * lifecycle hooks with Vitest-specific fields.
2070
+ */
2071
+ interface BenchFnOptions extends BenchOptions {
2072
+ /**
2073
+ * Path (relative to the project root) where the benchmark result is written
2074
+ * after a successful run. The string `${projectName}` is substituted with
2075
+ * the current project name. Absolute paths are accepted as long as they
2076
+ * resolve inside the project root.
2077
+ */
2078
+ writeResult?: string;
2079
+ /**
2080
+ * Mark this benchmark as a per-project entry. Per-project tasks still appear
2081
+ * in the inline comparison table for the current run, and Vitest additionally
2082
+ * collects them across projects and prints a single cross-project table at
2083
+ * the end of the run.
2084
+ */
2085
+ perProject?: boolean;
2086
+ }
2087
+ interface BenchRegistration<Name extends string> {
2088
+ name: Name;
2089
+ /**
2090
+ * The benchmark function. Absent for registrations created via `bench.from()`.
2091
+ */
2092
+ fn?: BenchFn;
2093
+ /**
2094
+ * Per-benchmark options (`beforeEach`, `beforeAll`, etc.). Absent for
2095
+ * registrations created via `bench.from()`.
2096
+ */
2097
+ fnOpts?: BenchOptions;
2098
+ run: (options?: BenchRunOptions) => Promise<BenchResult>;
2099
+ }
2100
+ interface BenchCompare {
2101
+ <Args extends BenchRegistration<any>[]>(...args: Args): Promise<BenchStorage<ExtractBenchNames<Args>>>;
2102
+ <Args extends BenchRegistration<any>[]>(...args: [...Args, BenchRunOptions]): Promise<BenchStorage<ExtractBenchNames<Args>>>;
2103
+ }
2104
+ interface BenchFactory {
2105
+ <Name extends string>(name: Name | Function, fn: BenchFn): BenchRegistration<Name>;
2106
+ <Name extends string>(name: Name | Function, options: BenchFnOptions, fn: BenchFn): BenchRegistration<Name>;
2107
+ }
2108
+ interface BenchFromSource {
2109
+ (): BaselineData | Promise<BaselineData>;
2110
+ }
2111
+ interface BenchFrom {
2112
+ <Name extends string>(name: Name | Function, source: string | BenchFromSource): BenchRegistration<Name>;
2113
+ }
2114
+ interface Bench extends BenchFactory {
2115
+ compare: BenchCompare;
2116
+ from: BenchFrom;
2117
+ }
2118
+
2119
+ interface TestFixtureItem extends FixtureOptions {
2120
+ name: string;
2121
+ value: unknown;
2122
+ scope: "test" | "file" | "worker";
2123
+ deps: Set<string>;
2124
+ parent?: TestFixtureItem;
2125
+ }
2126
+ type UserFixtures = Record<string, unknown>;
2127
+ type FixtureRegistrations = Map<string, TestFixtureItem>;
2128
+ declare class TestFixtures {
2129
+ private _suiteContexts;
2130
+ private _overrides;
2131
+ private _registrations;
2132
+ private static _definitions;
2133
+ private static _builtinFixtures;
2134
+ private static _fixtureOptionKeys;
2135
+ private static _fixtureScopes;
2136
+ private static _workerContextSuite;
2137
+ static clearDefinitions(): void;
2138
+ static getWorkerContexts(): Record<string, any>[];
2139
+ static getFileContexts(file: File): Record<string, any>[];
2140
+ static isFixtureOptions(obj: unknown): boolean;
2141
+ constructor(registrations?: FixtureRegistrations);
2142
+ extend(runner: VitestRunner, userFixtures: UserFixtures): TestFixtures;
2143
+ get(suite: Suite): FixtureRegistrations;
2144
+ override(runner: VitestRunner, userFixtures: UserFixtures): void;
2145
+ getFileContext(file: File): Record<string, any>;
2146
+ getWorkerContext(): Record<string, any>;
2147
+ private parseUserFixtures;
2148
+ }
2149
+
2150
+ /**
2151
+ * Registers a callback function to be executed once before all tests within the current suite.
2152
+ * 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.
2153
+ *
2154
+ * **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.
2155
+ *
2156
+ * @param {Function} fn - The callback function to be executed before all tests.
2157
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2158
+ * @returns {void}
2159
+ * @example
2160
+ * ```ts
2161
+ * // Example of using beforeAll to set up a database connection
2162
+ * beforeAll(async () => {
2163
+ * await database.connect();
2164
+ * });
2165
+ * ```
2166
+ */
2167
+ declare function beforeAll<ExtraContext = object>(this: unknown, fn: BeforeAllListener<ExtraContext>, timeout?: number): void;
2168
+ /**
2169
+ * Registers a callback function to be executed once after all tests within the current suite have completed.
2170
+ * 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.
2171
+ *
2172
+ * **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.
2173
+ *
2174
+ * @param {Function} fn - The callback function to be executed after all tests.
2175
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2176
+ * @returns {void}
2177
+ * @example
2178
+ * ```ts
2179
+ * // Example of using afterAll to close a database connection
2180
+ * afterAll(async () => {
2181
+ * await database.disconnect();
2182
+ * });
2183
+ * ```
2184
+ */
2185
+ declare function afterAll<ExtraContext = object>(this: unknown, fn: AfterAllListener<ExtraContext>, timeout?: number): void;
2186
+ /**
2187
+ * Registers a callback function to be executed before each test within the current suite.
2188
+ * 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.
2189
+ *
2190
+ * **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.
2191
+ *
2192
+ * @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
2193
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2194
+ * @returns {void}
2195
+ * @example
2196
+ * ```ts
2197
+ * // Example of using beforeEach to reset a database state
2198
+ * beforeEach(async () => {
2199
+ * await database.reset();
2200
+ * });
2201
+ * ```
2202
+ */
2203
+ declare function beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void;
2204
+ /**
2205
+ * Registers a callback function to be executed after each test within the current suite has completed.
2206
+ * 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.
2207
+ *
2208
+ * **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.
2209
+ *
2210
+ * @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
2211
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2212
+ * @returns {void}
2213
+ * @example
2214
+ * ```ts
2215
+ * // Example of using afterEach to delete temporary files created during a test
2216
+ * afterEach(async () => {
2217
+ * await fileSystem.deleteTempFiles();
2218
+ * });
2219
+ * ```
2220
+ */
2221
+ declare function afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void;
2222
+ /**
2223
+ * Registers a callback function to be executed when a test fails within the current suite.
2224
+ * This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
2225
+ *
2226
+ * **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.
2227
+ *
2228
+ * @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
2229
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2230
+ * @throws {Error} Throws an error if the function is not called within a test.
2231
+ * @returns {void}
2232
+ * @example
2233
+ * ```ts
2234
+ * // Example of using onTestFailed to log failure details
2235
+ * onTestFailed(({ errors }) => {
2236
+ * console.log(`Test failed: ${test.name}`, errors);
2237
+ * });
2238
+ * ```
2239
+ */
2240
+ declare const onTestFailed: TaskHook<OnTestFailedHandler>;
2241
+ /**
2242
+ * Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
2243
+ * This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
2244
+ *
2245
+ * 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`.
2246
+ *
2247
+ * **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.
2248
+ *
2249
+ * **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
2250
+ *
2251
+ * @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.
2252
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2253
+ * @throws {Error} Throws an error if the function is not called within a test.
2254
+ * @returns {void}
2255
+ * @example
2256
+ * ```ts
2257
+ * // Example of using onTestFinished for cleanup
2258
+ * const db = await connectToDatabase();
2259
+ * onTestFinished(async () => {
2260
+ * await db.disconnect();
2261
+ * });
2262
+ * ```
2263
+ */
2264
+ declare const onTestFinished: TaskHook<OnTestFinishedHandler>;
2265
+ /**
2266
+ * Registers a callback function that wraps around all tests within the current suite.
2267
+ * The callback receives a `runSuite` function that must be called to run the suite's tests.
2268
+ * This hook is useful for scenarios where you need to wrap an entire suite in a context
2269
+ * (e.g., starting a server, opening a database connection that all tests share).
2270
+ *
2271
+ * **Note:** When multiple `aroundAll` hooks are registered, they are nested inside each other.
2272
+ * The first registered hook is the outermost wrapper.
2273
+ *
2274
+ * @param {Function} fn - The callback function that wraps the suite. Must call `runSuite()` to run the tests.
2275
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2276
+ * @returns {void}
2277
+ * @example
2278
+ * ```ts
2279
+ * // Example of using aroundAll to wrap suite in a tracing span
2280
+ * aroundAll(async (runSuite) => {
2281
+ * await tracer.trace('test-suite', runSuite);
2282
+ * });
2283
+ * ```
2284
+ * @example
2285
+ * ```ts
2286
+ * // Example of using aroundAll with fixtures
2287
+ * aroundAll(async (runSuite, { db }) => {
2288
+ * await db.transaction(() => runSuite());
2289
+ * });
2290
+ * ```
2291
+ */
2292
+ declare function aroundAll<ExtraContext = object>(this: unknown, fn: AroundAllListener<ExtraContext>, timeout?: number): void;
2293
+ /**
2294
+ * Registers a callback function that wraps around each test within the current suite.
2295
+ * The callback receives a `runTest` function that must be called to run the test.
2296
+ * This hook is useful for scenarios where you need to wrap tests in a context (e.g., database transactions).
2297
+ *
2298
+ * **Note:** When multiple `aroundEach` hooks are registered, they are nested inside each other.
2299
+ * The first registered hook is the outermost wrapper.
2300
+ *
2301
+ * @param {Function} fn - The callback function that wraps the test. Must call `runTest()` to run the test.
2302
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2303
+ * @returns {void}
2304
+ * @example
2305
+ * ```ts
2306
+ * // Example of using aroundEach to wrap tests in a database transaction
2307
+ * aroundEach(async (runTest) => {
2308
+ * await database.transaction(() => runTest());
2309
+ * });
2310
+ * ```
2311
+ * @example
2312
+ * ```ts
2313
+ * // Example of using aroundEach with fixtures
2314
+ * aroundEach(async (runTest, { db }) => {
2315
+ * await db.transaction(() => runTest());
2316
+ * });
2317
+ * ```
2318
+ */
2319
+ declare function aroundEach<ExtraContext = object>(fn: AroundEachListener<ExtraContext>, timeout?: number): void;
2320
+
2321
+ type ChainableFunction<
2322
+ T extends string,
2323
+ F extends (...args: any) => any,
2324
+ C = object
2325
+ > = F & { [x in T]: ChainableFunction<T, F, C> } & {
2326
+ fn: (this: Record<T, any>, ...args: Parameters<F>) => ReturnType<F>;
2327
+ } & C;
2328
+ type TypedChainableFunction<
2329
+ T,
2330
+ F extends (...args: any) => any,
2331
+ C = object
2332
+ > = F & { [x in keyof T]: TypedChainableFunction<T, F, C> } & {
2333
+ fn: (this: Record<keyof T, any>, ...args: Parameters<F>) => ReturnType<F>;
2334
+ } & C;
2335
+ declare function createChainable<
2336
+ T extends string,
2337
+ Args extends any[],
2338
+ R = any
2339
+ >(keys: T[], fn: (this: Record<T, any>, ...args: Args) => R, context?: Record<string, any>): ChainableFunction<T, (...args: Args) => R>;
2340
+
2341
+ type RunMode = "run" | "skip" | "only" | "todo" | "queued";
2342
+ type TaskState = RunMode | "pass" | "fail";
2343
+ interface TaskBase {
2344
+ /**
2345
+ * Unique task identifier. Based on the file id and the position of the task.
2346
+ * The id of the file task is based on the file path relative to root and project name.
2347
+ * It will not change between runs.
2348
+ * @example `1201091390`, `1201091390_0`, `1201091390_0_1`
2349
+ */
2350
+ id: string;
2351
+ /**
2352
+ * Task name provided by the user. If no name was provided, it will be an empty string.
2353
+ */
2354
+ name: string;
2355
+ /**
2356
+ * Full name including the file path, any parent suites, and this task's name.
2357
+ *
2358
+ * Uses ` > ` as the separator between levels.
2359
+ *
2360
+ * @example
2361
+ * // file
2362
+ * 'test/task-names.test.ts'
2363
+ * @example
2364
+ * // suite
2365
+ * 'test/task-names.test.ts > meal planning'
2366
+ * 'test/task-names.test.ts > meal planning > grocery lists'
2367
+ * @example
2368
+ * // test
2369
+ * 'test/task-names.test.ts > meal planning > grocery lists > calculates ingredients'
2370
+ */
2371
+ fullName: string;
2372
+ /**
2373
+ * Full name excluding the file path, including any parent suites and this task's name. `undefined` for file tasks.
2374
+ *
2375
+ * Uses ` > ` as the separator between levels.
2376
+ *
2377
+ * @example
2378
+ * // file
2379
+ * undefined
2380
+ * @example
2381
+ * // suite
2382
+ * 'meal planning'
2383
+ * 'meal planning > grocery lists'
2384
+ * @example
2385
+ * // test
2386
+ * 'meal planning > grocery lists > calculates ingredients'
2387
+ */
2388
+ fullTestName?: string;
2389
+ /**
2390
+ * Task mode.
2391
+ * - **skip**: task is skipped
2392
+ * - **only**: only this task and other tasks with `only` mode will run
2393
+ * - **todo**: task is marked as a todo, alias for `skip`
2394
+ * - **run**: task will run or already ran
2395
+ * - **queued**: task will start running next. It can only exist on the File
2396
+ */
2397
+ mode: RunMode;
2398
+ /**
2399
+ * Custom metadata for the task. JSON reporter will save this data.
2400
+ */
2401
+ meta: TaskMeta;
2402
+ /**
2403
+ * Whether the task was produced with `.each()` method.
2404
+ */
2405
+ each?: boolean;
2406
+ /**
2407
+ * Whether the task should run concurrently with other tasks.
2408
+ */
2409
+ concurrent?: boolean;
2410
+ /**
2411
+ * Whether the tasks of the suite run in a random order.
2412
+ */
2413
+ shuffle?: boolean;
2414
+ /**
2415
+ * Suite that this task is part of. File task or the global suite will have no parent.
2416
+ */
2417
+ suite?: Suite;
2418
+ /**
2419
+ * Result of the task. Suite and file tasks will only have the result if there
2420
+ * was an error during collection or inside `afterAll`/`beforeAll`.
2421
+ */
2422
+ result?: TaskResult;
2423
+ /**
2424
+ * Retry configuration for the task.
2425
+ * - If a number, specifies how many times to retry
2426
+ * - If an object, allows fine-grained retry control
2427
+ * @default 0
2428
+ */
2429
+ retry?: Retry;
2430
+ /**
2431
+ * The amount of times the task should be repeated after the successful run.
2432
+ * If the task fails, it will not be retried unless `retry` is specified.
2433
+ * @default 0
2434
+ */
2435
+ repeats?: number;
2436
+ /**
2437
+ * Location of the task in the file. This field is populated only if
2438
+ * `includeTaskLocation` option is set. It is generated by calling `new Error`
2439
+ * and parsing the stack trace, so the location might differ depending on the runtime.
2440
+ */
2441
+ location?: Location;
2442
+ /**
2443
+ * If the test was collected by parsing the file AST, and the name
2444
+ * is not a static string, this property will be set to `true`.
2445
+ * @experimental
2446
+ */
2447
+ dynamic?: boolean;
2448
+ /**
2449
+ * Custom tags of the task. Useful for filtering tasks.
2450
+ */
2451
+ tags?: string[];
2452
+ logs?: UserConsoleLog[];
2453
+ }
2454
+ interface TaskPopulated extends TaskBase {
2455
+ /**
2456
+ * File task. It's the root task of the file.
2457
+ */
2458
+ file: File;
2459
+ /**
2460
+ * Whether the task should succeed if it fails. If the task fails, it will be marked as passed.
2461
+ */
2462
+ fails?: boolean;
2463
+ /**
2464
+ * Store promises (from async expects) to wait for them before finishing the test
2465
+ */
2466
+ promises?: Promise<any>[];
2467
+ }
2468
+ /**
2469
+ * Custom metadata that can be used in reporters.
2470
+ */
2471
+ interface TaskMeta {
2472
+ typecheck?: boolean;
2473
+ benchmark?: boolean;
2474
+ __vitest_label__?: string;
2475
+ }
2476
+ /**
2477
+ * The result of an individual test attempt.
2478
+ */
2479
+ interface TaskResultAttempt {
2480
+ /** The state after applying the test's expected failure option. */
2481
+ state: "pass" | "fail" | "skip";
2482
+ /** Errors produced by this attempt. */
2483
+ errors?: TestError[];
2484
+ /** How long in milliseconds the attempt took to run. */
2485
+ duration: number;
2486
+ /** Time in milliseconds when the attempt started running. */
2487
+ startTime: number;
2488
+ /** The zero-based retry index within the repeat. */
2489
+ retryIndex: number;
2490
+ /** The zero-based repeat index. */
2491
+ repeatIndex: number;
2492
+ }
2493
+ /**
2494
+ * The result of calling a task.
2495
+ */
2496
+ interface TaskResult {
2497
+ /**
2498
+ * State of the task. Inherits the `task.mode` during collection.
2499
+ * When the task has finished, it will be changed to `pass` or `fail`.
2500
+ * - **pass**: task ran successfully
2501
+ * - **fail**: task failed
2502
+ */
2503
+ state: TaskState;
2504
+ /**
2505
+ * Errors that occurred during the task execution. It is possible to have several errors
2506
+ * if `expect.soft()` failed multiple times or `retry` was triggered.
2507
+ */
2508
+ errors?: TestError[];
2509
+ /**
2510
+ * Individual results for every retry and repeat attempt.
2511
+ */
2512
+ attempts?: TaskResultAttempt[];
2513
+ /**
2514
+ * How long in milliseconds the task took to run.
2515
+ */
2516
+ duration?: number;
2517
+ /**
2518
+ * Time in milliseconds when the task started running.
2519
+ */
2520
+ startTime?: number;
2521
+ /**
2522
+ * Heap size in bytes after the task finished.
2523
+ * Only available if `logHeapUsage` option is set and `process.memoryUsage` is defined.
2524
+ */
2525
+ heap?: number;
2526
+ /**
2527
+ * State of related to this task hooks. Useful during reporting.
2528
+ */
2529
+ hooks?: Partial<Record<keyof SuiteHooks, TaskState>>;
2530
+ /**
2531
+ * The number of times the task has been retried across all repeats.
2532
+ */
2533
+ retryCount?: number;
2534
+ /**
2535
+ * The zero-based index of the current repeat.
2536
+ */
2537
+ repeatCount?: number;
2538
+ }
2539
+ /** The time spent importing & executing a non-externalized file. */
2540
+ interface ImportDuration {
2541
+ /** The time spent importing & executing the file itself, not counting all non-externalized imports that the file does. */
2542
+ selfTime: number;
2543
+ /** The time spent importing & executing the file and all its imports. */
2544
+ totalTime: number;
2545
+ /** Will be set to `true`, if the module was externalized. In this case totalTime and selfTime are identical. */
2546
+ external?: boolean;
2547
+ /** Which module imported this module first. All subsequent imports are cached. */
2548
+ importer?: string;
2549
+ }
2550
+ /**
2551
+ * The tuple representing a single task update.
2552
+ * Usually reported after the task finishes.
2553
+ */
2554
+ type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta];
2555
+ interface TaskEventData {
2556
+ annotation?: TestAnnotation | undefined;
2557
+ artifact?: TestArtifact | undefined;
2558
+ }
2559
+ type TaskEventPack = [id: string, event: TaskUpdateEvent, data: TaskEventData | undefined];
2560
+ 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";
2561
+ interface Suite extends TaskBase {
2562
+ type: "suite";
2563
+ /**
2564
+ * File task. It's the root task of the file.
2565
+ */
2566
+ file: File;
2567
+ /**
2568
+ * An array of tasks that are part of the suite.
2569
+ */
2570
+ tasks: Task[];
2571
+ }
2572
+ interface File extends Suite {
2573
+ /**
2574
+ * The name of the pool that the file belongs to.
2575
+ * @default 'forks'
2576
+ */
2577
+ pool?: string;
2578
+ /**
2579
+ * The environment that processes the file on the server.
2580
+ */
2581
+ viteEnvironment?: string;
2582
+ /**
2583
+ * The path to the file in UNIX format.
2584
+ */
2585
+ filepath: string;
2586
+ /**
2587
+ * The name of the workspace project the file belongs to.
2588
+ */
2589
+ projectName: string | undefined;
2590
+ /**
2591
+ * The time it took to collect all tests in the file.
2592
+ * This time also includes importing all the file dependencies.
2593
+ */
2594
+ collectDuration?: number;
2595
+ /**
2596
+ * The portion of `collectDuration` the worker spent waiting for the server
2597
+ * to resolve and transform modules.
2598
+ */
2599
+ collectFetchDuration?: number;
2600
+ /**
2601
+ * The time it took to import the setup file.
2602
+ */
2603
+ setupDuration?: number;
2604
+ /**
2605
+ * The portion of `setupDuration` the worker spent waiting for the server
2606
+ * to resolve and transform modules.
2607
+ */
2608
+ setupFetchDuration?: number;
2609
+ /** The time spent importing every non-externalized dependency that Vitest has processed. */
2610
+ importDurations?: Record<string, ImportDuration>;
2611
+ prepareDuration?: number;
2612
+ environmentLoad?: number;
2613
+ concurrencyId: number;
2614
+ workerId: number;
2615
+ }
2616
+ interface Test<ExtraContext = object> extends TaskPopulated {
2617
+ type: "test";
2618
+ /**
2619
+ * Test context that will be passed to the test function.
2620
+ */
2621
+ context: TestContext & ExtraContext;
2622
+ /**
2623
+ * The test timeout in milliseconds.
2624
+ */
2625
+ timeout: number;
2626
+ /**
2627
+ * An array of custom annotations.
2628
+ */
2629
+ annotations: TestAnnotation[];
2630
+ /**
2631
+ * An array of artifacts produced by the test.
2632
+ *
2633
+ * @experimental
2634
+ */
2635
+ artifacts: TestArtifact[];
2636
+ fullTestName: string;
2637
+ /**
2638
+ * An array of benchmark results generated by `context.bench` function.
2639
+ * The benchmark is added only after `bench().run` or `bench.compare` is resolved.
2640
+ *
2641
+ * @experimental
2642
+ */
2643
+ benchmarks: TestBenchmark[];
2644
+ }
2645
+ interface TestBenchmark {
2646
+ name: string;
2647
+ tasks: TestBenchmarkTask[];
2648
+ }
2649
+ type TestBenchmarkStatistics = Statistics;
2650
+ interface BaselineData {
2651
+ latency: TestBenchmarkStatistics;
2652
+ throughput: TestBenchmarkStatistics;
2653
+ period: number;
2654
+ totalTime: number;
2655
+ }
2656
+ interface TestBenchmarkTask {
2657
+ name: string;
2658
+ latency: TestBenchmarkStatistics;
2659
+ throughput: TestBenchmarkStatistics;
2660
+ period: number;
2661
+ totalTime: number;
2662
+ rank: number;
2663
+ perProject?: boolean;
2664
+ /**
2665
+ * `true` when the task was produced by `bench.from()` rather than by
2666
+ * executing a function. Reporters can use this to render the row as a
2667
+ * static reference (no margin of error, no samples).
2668
+ */
2669
+ fromStore?: boolean;
2670
+ }
2671
+ type Task = Test | Suite | File;
2672
+ type TestFunction<ExtraContext = object> = (context: TestContext & ExtraContext) => Awaitable<any> | void;
2673
+ type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
2674
+ 1: [T[0]];
2675
+ 2: [T[0], T[1]];
2676
+ 3: [T[0], T[1], T[2]];
2677
+ 4: [T[0], T[1], T[2], T[3]];
2678
+ 5: [T[0], T[1], T[2], T[3], T[4]];
2679
+ 6: [T[0], T[1], T[2], T[3], T[4], T[5]];
2680
+ 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]];
2681
+ 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]];
2682
+ 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]];
2683
+ 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]];
2684
+ fallback: Array<T extends ReadonlyArray<infer U> ? U : any>;
2685
+ }[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"];
2686
+ interface EachFunctionReturn<T extends any[]> {
2687
+ (name: string | Function, fn: (...args: T) => Awaitable<void>, options?: number): void;
2688
+ (name: string | Function, options: TestCollectorOptions, fn: (...args: T) => Awaitable<void>): void;
2689
+ }
2690
+ interface TestEachFunction {
2691
+ <T extends any[] | [any]>(cases: ReadonlyArray<T>): EachFunctionReturn<T>;
2692
+ <T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): EachFunctionReturn<ExtractEachCallbackArgs<T>>;
2693
+ <T>(cases: ReadonlyArray<T>): EachFunctionReturn<T[]>;
2694
+ (...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
2695
+ }
2696
+ interface TestForFunctionReturn<
2697
+ Arg,
2698
+ Context
2699
+ > {
2700
+ (name: string | Function, fn: (arg: Arg, context: Context) => Awaitable<void>): void;
2701
+ (name: string | Function, options: TestCollectorOptions, fn: (args: Arg, context: Context) => Awaitable<void>): void;
2702
+ }
2703
+ interface TestForFunction<ExtraContext> {
2704
+ <T>(cases: ReadonlyArray<T>): TestForFunctionReturn<T, TestContext & ExtraContext>;
2705
+ (strings: TemplateStringsArray, ...values: any[]): TestForFunctionReturn<any, TestContext & ExtraContext>;
2706
+ }
2707
+ interface SuiteForFunction {
2708
+ <T>(cases: ReadonlyArray<T>): EachFunctionReturn<[T]>;
2709
+ (...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
2710
+ }
2711
+ interface TestCollectorCallable<C = object> {
2712
+ <ExtraContext extends C>(name: string | Function, fn?: TestFunction<ExtraContext>, options?: number): void;
2713
+ <ExtraContext extends C>(name: string | Function, options?: TestCollectorOptions, fn?: TestFunction<ExtraContext>): void;
2714
+ }
2715
+ type ChainableTestContextMap = Pick<Required<TestOptions>, "concurrent" | "only" | "skip" | "todo" | "fails">;
2716
+ type ChainableTestAPI<ExtraContext = object> = TypedChainableFunction<ChainableTestContextMap, TestCollectorCallable<ExtraContext>, {
2717
+ each: TestEachFunction;
2718
+ for: TestForFunction<ExtraContext>;
2719
+ }>;
2720
+ type TestCollectorOptions = Omit<TestOptions, "shuffle">;
2721
+ /**
2722
+ * Retry configuration for tests.
2723
+ * Can be a number for simple retry count, or an object for advanced retry control.
2724
+ */
2725
+ type Retry = number | {
2726
+ /**
2727
+ * The number of times to retry the test if it fails.
2728
+ * @default 0
2729
+ */
2730
+ count?: number;
2731
+ /**
2732
+ * Delay in milliseconds between retry attempts.
2733
+ * @default 0
2734
+ */
2735
+ delay?: number;
2736
+ /**
2737
+ * Condition to determine if a test should be retried based on the error.
2738
+ * - If a RegExp, it is tested against the error message
2739
+ * - If a function, called with the TestError object; return true to retry
2740
+ *
2741
+ * NOTE: Functions can only be used in test files, not in vitest.config.ts,
2742
+ * because the configuration is serialized when passed to worker threads.
2743
+ *
2744
+ * @default undefined (retry on all errors)
2745
+ */
2746
+ condition?: RegExp | ((error: TestError) => boolean);
2747
+ };
2748
+ /**
2749
+ * Serializable retry configuration (used in config files).
2750
+ * Functions cannot be serialized, so only string conditions are allowed.
2751
+ */
2752
+ type SerializableRetry = number | {
2753
+ /**
2754
+ * The number of times to retry the test if it fails.
2755
+ * @default 0
2756
+ */
2757
+ count?: number;
2758
+ /**
2759
+ * Delay in milliseconds between retry attempts.
2760
+ * @default 0
2761
+ */
2762
+ delay?: number;
2763
+ /**
2764
+ * Condition to determine if a test should be retried based on the error.
2765
+ * Must be a RegExp tested against the error message.
2766
+ *
2767
+ * @default undefined (retry on all errors)
2768
+ */
2769
+ condition?: RegExp;
2770
+ };
2771
+ interface TestOptions {
2772
+ /**
2773
+ * Test timeout.
2774
+ */
2775
+ timeout?: number;
2776
+ /**
2777
+ * Retry configuration for the test.
2778
+ * - If a number, specifies how many times to retry
2779
+ * - If an object, allows fine-grained retry control
2780
+ * @default 0
2781
+ */
2782
+ retry?: Retry;
2783
+ /**
2784
+ * How many times the test will run again.
2785
+ * Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default.
2786
+ *
2787
+ * @default 0
2788
+ */
2789
+ repeats?: number;
2790
+ /**
2791
+ * Whether suites and tests run concurrently.
2792
+ * Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`.
2793
+ */
2794
+ concurrent?: boolean;
2795
+ /**
2796
+ * Whether the test should be skipped.
2797
+ */
2798
+ skip?: boolean;
2799
+ /**
2800
+ * Should this test be the only one running in a suite.
2801
+ */
2802
+ only?: boolean;
2803
+ /**
2804
+ * Whether the test should be skipped and marked as a todo.
2805
+ */
2806
+ todo?: boolean;
2807
+ /**
2808
+ * Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail.
2809
+ */
2810
+ fails?: boolean;
2811
+ /**
2812
+ * Custom tags of the test. Useful for filtering tests.
2813
+ */
2814
+ tags?: keyof TestTags extends never ? string[] | string : TestTags[keyof TestTags] | TestTags[keyof TestTags][];
2815
+ /**
2816
+ * Custom test metadata available to reporters.
2817
+ */
2818
+ meta?: Partial<TaskMeta>;
2819
+ }
2820
+ interface TestTags {}
2821
+ interface TestTagDefinition extends Omit<TestOptions, "tags" | "shuffle"> {
2822
+ /**
2823
+ * The name of the tag. This is what you use in the `tags` array in tests.
2824
+ */
2825
+ name: keyof TestTags extends never ? string : TestTags[keyof TestTags];
2826
+ /**
2827
+ * A description for the tag. This will be shown in the CLI help and UI.
2828
+ */
2829
+ description?: string;
2830
+ /**
2831
+ * Priority for merging options when multiple tags with the same options are applied to a test.
2832
+ *
2833
+ * Lower number means higher priority. E.g., priority 1 takes precedence over priority 3.
2834
+ */
2835
+ priority?: number;
2836
+ }
2837
+ interface SuiteOptions extends TestOptions {
2838
+ /**
2839
+ * Whether the tasks of the suite run in a random order.
2840
+ */
2841
+ shuffle?: boolean;
2842
+ }
2843
+ interface ExtendedAPI<ExtraContext> {
2844
+ skipIf: (condition: any) => ChainableTestAPI<ExtraContext>;
2845
+ runIf: (condition: any) => ChainableTestAPI<ExtraContext>;
2846
+ }
2847
+ interface Hooks<ExtraContext> {
2848
+ /**
2849
+ * Suite-level hooks only receive file/worker scoped fixtures.
2850
+ * Test-scoped fixtures are NOT available in beforeAll/afterAll/aroundAll.
2851
+ */
2852
+ beforeAll: typeof beforeAll<ExtractSuiteContext<ExtraContext>>;
2853
+ afterAll: typeof afterAll<ExtractSuiteContext<ExtraContext>>;
2854
+ aroundAll: typeof aroundAll<ExtractSuiteContext<ExtraContext>>;
2855
+ /**
2856
+ * Test-level hooks receive all fixtures including test-scoped ones.
2857
+ */
2858
+ beforeEach: typeof beforeEach<ExtraContext>;
2859
+ afterEach: typeof afterEach<ExtraContext>;
2860
+ aroundEach: typeof aroundEach<ExtraContext>;
2861
+ }
2862
+ type TestAPI<ExtraContext = object> = ChainableTestAPI<ExtraContext> & ExtendedAPI<ExtraContext> & Hooks<ExtraContext> & {
2863
+ /**
2864
+ * Extend the test API with custom fixtures.
2865
+ *
2866
+ * @example
2867
+ * ```ts
2868
+ * // Simple test fixtures (backward compatible)
2869
+ * const myTest = test.extend<{ foo: string }>({
2870
+ * foo: 'value',
2871
+ * })
2872
+ *
2873
+ * // With scoped fixtures - use $test/$file/$worker structure
2874
+ * const myTest = test.extend<{
2875
+ * $test: { testData: string }
2876
+ * $file: { fileDb: Database }
2877
+ * $worker: { workerConfig: Config }
2878
+ * }>({
2879
+ * testData: async ({ fileDb }, use) => {
2880
+ * await use(await fileDb.getData())
2881
+ * },
2882
+ * fileDb: [async ({ workerConfig }, use) => {
2883
+ * // File fixture can only access workerConfig, NOT testData
2884
+ * const db = new Database(workerConfig)
2885
+ * await use(db)
2886
+ * await db.close()
2887
+ * }, { scope: 'file' }],
2888
+ * workerConfig: [async ({}, use) => {
2889
+ * // Worker fixture can only access other worker fixtures
2890
+ * await use(loadConfig())
2891
+ * }, { scope: 'worker' }],
2892
+ * })
2893
+ *
2894
+ * // Builder pattern with automatic type inference
2895
+ * const myTest = test
2896
+ * .extend('config', { scope: 'worker' }, async ({}) => {
2897
+ * return { port: 3000 } // Type inferred as { port: number }
2898
+ * })
2899
+ * .extend('db', { scope: 'file' }, async ({ config }, { onCleanup }) => {
2900
+ * // TypeScript knows config is { port: number }
2901
+ * const db = new Database(config.port)
2902
+ * onCleanup(() => db.close()) // Register cleanup
2903
+ * return db // Type inferred as Database
2904
+ * })
2905
+ * .extend('data', async ({ db }) => {
2906
+ * // TypeScript knows db is Database
2907
+ * return await db.getData() // Type inferred from return
2908
+ * })
2909
+ * ```
2910
+ */
2911
+ extend: {
2912
+ <
2913
+ K extends string,
2914
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2915
+ >(name: K, options: WorkerScopeFixtureOptions, fn: BuilderFixtureFn<T, WorkerScopeContext<ExtraContext>>): TestAPI<AddBuilderWorker<ExtraContext, K, T>>;
2916
+ <
2917
+ K extends string,
2918
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2919
+ >(name: K, options: FileScopeFixtureOptions, fn: BuilderFixtureFn<T, FileScopeContext<ExtraContext>>): TestAPI<AddBuilderFile<ExtraContext, K, T>>;
2920
+ <
2921
+ K extends string,
2922
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2923
+ >(name: K, options: TestScopeFixtureOptions, fn: BuilderFixtureFn<T, TestScopeContext<ExtraContext>>): TestAPI<AddBuilderTest<ExtraContext, K, T>>;
2924
+ <
2925
+ K extends string,
2926
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2927
+ >(name: K, fn: BuilderFixtureFn<T, TestScopeContext<ExtraContext>>): TestAPI<AddBuilderTest<ExtraContext, K, T>>;
2928
+ <
2929
+ K extends string,
2930
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2931
+ >(name: K, options: WorkerScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI<AddBuilderWorker<ExtraContext, K, T>>;
2932
+ <
2933
+ K extends string,
2934
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2935
+ >(name: K, options: FileScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI<AddBuilderFile<ExtraContext, K, T>>;
2936
+ <
2937
+ K extends string,
2938
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2939
+ >(name: K, options: TestScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI<AddBuilderTest<ExtraContext, K, T>>;
2940
+ <
2941
+ K extends string,
2942
+ T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown)
2943
+ >(name: K, value: T extends (...args: any[]) => any ? never : T): TestAPI<AddBuilderTest<ExtraContext, K, T>>;
2944
+ <T extends ScopedFixturesDef>(fixtures: ScopedFixturesObject<T, ExtraContext>): TestAPI<ExtractScopedFixtures<T> & ExtraContext>;
2945
+ <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 }>;
2946
+ };
2947
+ /**
2948
+ * Overwrite fixture values for the current suite scope.
2949
+ * Supports both object syntax and builder pattern.
2950
+ *
2951
+ * @example
2952
+ * ```ts
2953
+ * describe('with custom config', () => {
2954
+ * // Object syntax
2955
+ * test.override({ config: { port: 4000 } })
2956
+ *
2957
+ * // Builder pattern - value
2958
+ * test.override('config', { port: 4000 })
2959
+ *
2960
+ * // Builder pattern - function
2961
+ * test.override('config', () => ({ port: 4000 }))
2962
+ *
2963
+ * // Builder pattern - function with cleanup
2964
+ * test.override('db', async ({ config }, { onCleanup }) => {
2965
+ * const db = await createDb(config)
2966
+ * onCleanup(() => db.close())
2967
+ * return db
2968
+ * })
2969
+ * })
2970
+ * ```
2971
+ */
2972
+ override: {
2973
+ <K extends keyof ExtraContext>(name: K, options: FixtureOptions, fn: BuilderFixtureFn<ExtraContext[K], ExtraContext & TestContext>): TestAPI<ExtraContext>;
2974
+ <K extends keyof ExtraContext>(name: K, fn: BuilderFixtureFn<ExtraContext[K], ExtraContext & TestContext>): TestAPI<ExtraContext>;
2975
+ <K extends keyof ExtraContext>(name: K, options: FixtureOptions, value: ExtraContext[K] extends (...args: any[]) => any ? never : ExtraContext[K]): TestAPI<ExtraContext>;
2976
+ <K extends keyof ExtraContext>(name: K, value: ExtraContext[K] extends (...args: any[]) => any ? never : ExtraContext[K]): TestAPI<ExtraContext>;
2977
+ (fixtures: Partial<Fixtures<ExtraContext>>): TestAPI<ExtraContext>;
2978
+ };
2979
+ /**
2980
+ * @deprecated Use `test.override()` instead
2981
+ */
2982
+ scoped: (fixtures: Partial<Fixtures<ExtraContext>>) => TestAPI<ExtraContext>;
2983
+ describe: SuiteAPI<ExtraContext>;
2984
+ suite: SuiteAPI<ExtraContext>;
2985
+ };
2986
+ interface FixtureOptions {
2987
+ /**
2988
+ * Whether to automatically set up current fixture, even though it's not being used.
2989
+ * Test-scoped auto fixtures are not initialized in suite-level hooks (`beforeAll`/`afterAll`/`aroundAll`).
2990
+ * @default false
2991
+ */
2992
+ auto?: boolean;
2993
+ /**
2994
+ * Indicated if the injected value from the config should be preferred over the fixture value
2995
+ */
2996
+ injected?: boolean;
2997
+ /**
2998
+ * When should the fixture be set up.
2999
+ * - **test**: fixture will be set up before every test
3000
+ * - **worker**: fixture will be set up once per worker
3001
+ * - **file**: fixture will be set up once per file
3002
+ *
3003
+ * **Warning:** The `vmThreads` and `vmForks` pools initiate worker fixtures once per test file.
3004
+ * @default 'test'
3005
+ */
3006
+ scope?: "test" | "worker" | "file";
3007
+ }
3008
+ /**
3009
+ * Options for test-scoped fixtures.
3010
+ * Test fixtures are set up before each test and have access to all fixtures.
3011
+ */
3012
+ interface TestScopeFixtureOptions extends Omit<FixtureOptions, "scope"> {
3013
+ /**
3014
+ * @default 'test'
3015
+ */
3016
+ scope?: "test";
3017
+ }
3018
+ /**
3019
+ * Options for file-scoped fixtures.
3020
+ * File fixtures are set up once per file and can only access other file fixtures and worker fixtures.
3021
+ */
3022
+ interface FileScopeFixtureOptions extends Omit<FixtureOptions, "scope"> {
3023
+ /**
3024
+ * Must be 'file' for file-scoped fixtures.
3025
+ */
3026
+ scope: "file";
3027
+ }
3028
+ /**
3029
+ * Options for worker-scoped fixtures.
3030
+ * Worker fixtures are set up once per worker and can only access other worker fixtures.
3031
+ */
3032
+ interface WorkerScopeFixtureOptions extends Omit<FixtureOptions, "scope"> {
3033
+ /**
3034
+ * Must be 'worker' for worker-scoped fixtures.
3035
+ */
3036
+ scope: "worker";
3037
+ }
3038
+ type Use<T> = (value: T) => Promise<void>;
3039
+ /**
3040
+ * Cleanup registration function for builder pattern fixtures.
3041
+ * Call this to register a cleanup function that runs after the test/file/worker completes.
3042
+ *
3043
+ * **Note:** This function can only be called once per fixture. If you need multiple
3044
+ * cleanup operations, either combine them into a single cleanup function or split
3045
+ * your fixture into multiple smaller fixtures.
3046
+ */
3047
+ type OnCleanup = (cleanup: () => Awaitable<void>) => void;
3048
+ /**
3049
+ * Builder pattern fixture function with automatic type inference.
3050
+ * Returns the fixture value directly (type is inferred from return).
3051
+ * Use onCleanup to register teardown logic.
3052
+ *
3053
+ * Parameters can be omitted if not needed:
3054
+ * - `async () => value` - no dependencies, no cleanup
3055
+ * - `async ({ dep }) => value` - with dependencies, no cleanup
3056
+ * - `async ({ dep }, { onCleanup }) => value` - with dependencies and cleanup
3057
+ */
3058
+ type BuilderFixtureFn<
3059
+ T,
3060
+ Context
3061
+ > = (context: Context, fixture: {
3062
+ onCleanup: OnCleanup;
3063
+ }) => T | Promise<T>;
3064
+ type ExtractSuiteContext<C> = C extends {
3065
+ $__worker?: any;
3066
+ } | {
3067
+ $__file?: any;
3068
+ } | {
3069
+ $__test?: any;
3070
+ } ? ExtractBuilderWorker<C> & ExtractBuilderFile<C> : C;
3071
+ /**
3072
+ * Extracts worker-scoped fixtures from a context that includes scope info.
3073
+ */
3074
+ type ExtractBuilderWorker<C> = C extends {
3075
+ $__worker?: infer W;
3076
+ } ? W extends Record<string, any> ? W : object : object;
3077
+ /**
3078
+ * Extracts file-scoped fixtures from a context that includes scope info.
3079
+ */
3080
+ type ExtractBuilderFile<C> = C extends {
3081
+ $__file?: infer F;
3082
+ } ? F extends Record<string, any> ? F : object : object;
3083
+ /**
3084
+ * Extracts test-scoped fixtures from a context that includes scope info.
3085
+ */
3086
+ type ExtractBuilderTest<C> = C extends {
3087
+ $__test?: infer T;
3088
+ } ? T extends Record<string, any> ? T : object : object;
3089
+ /**
3090
+ * Adds a worker fixture to the context with proper scope tracking.
3091
+ */
3092
+ type AddBuilderWorker<
3093
+ C,
3094
+ K extends string,
3095
+ V
3096
+ > = Omit<C, "$__worker"> & Record<K, V> & {
3097
+ readonly $__worker?: ExtractBuilderWorker<C> & Record<K, V>;
3098
+ readonly $__file?: ExtractBuilderFile<C>;
3099
+ readonly $__test?: ExtractBuilderTest<C>;
3100
+ };
3101
+ /**
3102
+ * Adds a file fixture to the context with proper scope tracking.
3103
+ */
3104
+ type AddBuilderFile<
3105
+ C,
3106
+ K extends string,
3107
+ V
3108
+ > = Omit<C, "$__file"> & Record<K, V> & {
3109
+ readonly $__worker?: ExtractBuilderWorker<C>;
3110
+ readonly $__file?: ExtractBuilderFile<C> & Record<K, V>;
3111
+ readonly $__test?: ExtractBuilderTest<C>;
3112
+ };
3113
+ /**
3114
+ * Adds a test fixture to the context with proper scope tracking.
3115
+ */
3116
+ type AddBuilderTest<
3117
+ C,
3118
+ K extends string,
3119
+ V
3120
+ > = Omit<C, "$__test"> & Record<K, V> & {
3121
+ readonly $__worker?: ExtractBuilderWorker<C>;
3122
+ readonly $__file?: ExtractBuilderFile<C>;
3123
+ readonly $__test?: ExtractBuilderTest<C> & Record<K, V>;
3124
+ };
3125
+ /**
3126
+ * Context available to worker-scoped fixtures.
3127
+ * Worker fixtures can only access other worker fixtures.
3128
+ * They do NOT have access to test context (task, expect, onTestFailed, etc.)
3129
+ * since they run once per worker, outside of any specific test.
3130
+ */
3131
+ type WorkerScopeContext<C> = ExtractBuilderWorker<C>;
3132
+ /**
3133
+ * Context available to file-scoped fixtures.
3134
+ * File fixtures can access worker and other file fixtures.
3135
+ * They do NOT have access to test context (task, expect, onTestFailed, etc.)
3136
+ * since they run once per file, outside of any specific test.
3137
+ */
3138
+ type FileScopeContext<C> = ExtractBuilderWorker<C> & ExtractBuilderFile<C>;
3139
+ /**
3140
+ * Context available to test-scoped fixtures (all fixtures + test context).
3141
+ */
3142
+ type TestScopeContext<C> = C & TestContext;
3143
+ type FixtureFn<
3144
+ T,
3145
+ K extends keyof T,
3146
+ ExtraContext
3147
+ > = (context: Omit<T, K> & ExtraContext, use: Use<T[K]>) => Promise<void>;
3148
+ type Fixture<
3149
+ T,
3150
+ K extends keyof T,
3151
+ ExtraContext = object
3152
+ > = ((...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);
3153
+ /**
3154
+ * Fixture function with explicit context type for scoped fixtures.
3155
+ */
3156
+ type ScopedFixtureFn<
3157
+ Value,
3158
+ Context
3159
+ > = (context: Context, use: Use<Value>) => Promise<void>;
3160
+ /**
3161
+ * Fixtures definition for backward compatibility.
3162
+ * All fixtures are in T and any scope is allowed.
3163
+ */
3164
+ type Fixtures<
3165
+ T,
3166
+ ExtraContext = object
3167
+ > = { [K in keyof T]: Fixture<T, K, ExtraContext & TestContext> | [Fixture<T, K, ExtraContext & TestContext>, FixtureOptions?] };
3168
+ /**
3169
+ * Scoped fixtures definition using a single generic with optional scope keys.
3170
+ * This provides better ergonomics than multiple generics.
3171
+ * Uses $ prefix to avoid conflicts with fixture names.
3172
+ *
3173
+ * @example
3174
+ * ```ts
3175
+ * test.extend<{
3176
+ * $worker?: { config: Config }
3177
+ * $file?: { db: Database }
3178
+ * $test?: { data: string }
3179
+ * }>({ ... })
3180
+ * ```
3181
+ */
3182
+ interface ScopedFixturesDef {
3183
+ $test?: Record<string, any>;
3184
+ $file?: Record<string, any>;
3185
+ $worker?: Record<string, any>;
3186
+ }
3187
+ /**
3188
+ * Extracts fixture types from a ScopedFixturesDef.
3189
+ * Handles optional properties by using Exclude to remove undefined.
3190
+ */
3191
+ 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>);
3192
+ /**
3193
+ * Creates the fixtures object type for ScopedFixturesDef with proper scope validation.
3194
+ * - Test fixtures: can be defined as value, function, or tuple with optional scope
3195
+ * - File fixtures: MUST have { scope: 'file' }
3196
+ * - Worker fixtures: MUST have { scope: 'worker' }
3197
+ */
3198
+ type ScopedFixturesObject<
3199
+ T extends ScopedFixturesDef,
3200
+ ExtraContext = object
3201
+ > = { [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] };
3202
+ interface SuiteCollectorCallable<ExtraContext = object> {
3203
+ <OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, fn?: SuiteFactory<OverrideExtraContext>, options?: number): SuiteCollector<OverrideExtraContext>;
3204
+ <OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, options: SuiteOptions, fn?: SuiteFactory<OverrideExtraContext>): SuiteCollector<OverrideExtraContext>;
3205
+ }
3206
+ type ChainableSuiteContextMap = Pick<Required<SuiteOptions>, "concurrent" | "only" | "skip" | "todo" | "shuffle">;
3207
+ type ChainableSuiteAPI<ExtraContext = object> = TypedChainableFunction<ChainableSuiteContextMap, SuiteCollectorCallable<ExtraContext>, {
3208
+ each: TestEachFunction;
3209
+ for: SuiteForFunction;
3210
+ }>;
3211
+ type SuiteAPI<ExtraContext = object> = ChainableSuiteAPI<ExtraContext> & {
3212
+ skipIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
3213
+ runIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
3214
+ };
3215
+ interface BeforeAllListener<ExtraContext = object> {
3216
+ (context: ExtraContext, suite: Readonly<Suite | File>): Awaitable<unknown>;
3217
+ }
3218
+ interface AfterAllListener<ExtraContext = object> {
3219
+ (context: ExtraContext, suite: Readonly<Suite | File>): Awaitable<unknown>;
3220
+ }
3221
+ interface BeforeEachListener<ExtraContext = object> {
3222
+ (context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
3223
+ }
3224
+ interface AfterEachListener<ExtraContext = object> {
3225
+ (context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
3226
+ }
3227
+ interface AroundEachListener<ExtraContext = object> {
3228
+ (runTest: () => Promise<void>, context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
3229
+ }
3230
+ interface AroundAllListener<ExtraContext = object> {
3231
+ (runSuite: () => Promise<void>, context: ExtraContext, suite: Readonly<Suite | File>): Awaitable<unknown>;
3232
+ }
3233
+ interface RegisteredAllListener {
3234
+ (suite: Readonly<Suite | File>): Awaitable<unknown>;
3235
+ }
3236
+ interface RegisteredAroundAllListener {
3237
+ (runSuite: () => Promise<void>, suite: Readonly<Suite | File>): Awaitable<unknown>;
3238
+ }
3239
+ interface SuiteHooks<ExtraContext = object> {
3240
+ beforeAll: RegisteredAllListener[];
3241
+ afterAll: RegisteredAllListener[];
3242
+ aroundAll: RegisteredAroundAllListener[];
3243
+ beforeEach: BeforeEachListener<ExtraContext>[];
3244
+ afterEach: AfterEachListener<ExtraContext>[];
3245
+ aroundEach: AroundEachListener<ExtraContext>[];
3246
+ }
3247
+ interface TaskCustomOptions extends TestOptions {
3248
+ /**
3249
+ * Whether the task was produced with `.each()` method.
3250
+ */
3251
+ each?: boolean;
3252
+ /**
3253
+ * Task fixtures.
3254
+ */
3255
+ fixtures?: TestFixtures;
3256
+ /**
3257
+ * Function that will be called when the task is executed.
3258
+ * If nothing is provided, the runner will try to get the function using `getFn(task)`.
3259
+ * If the runner cannot find the function, the task will be marked as failed.
3260
+ */
3261
+ handler?: (context: TestContext) => Awaitable<void>;
3262
+ }
3263
+ interface SuiteCollector<ExtraContext = object> {
3264
+ readonly name: string;
3265
+ readonly mode: RunMode;
3266
+ options?: SuiteOptions;
3267
+ type: "collector";
3268
+ test: TestAPI<ExtraContext>;
3269
+ tasks: (Suite | Test<ExtraContext> | SuiteCollector<ExtraContext>)[];
3270
+ file: File;
3271
+ suite?: Suite;
3272
+ task: (name: string, options?: TaskCustomOptions) => Test<ExtraContext>;
3273
+ collect: (file: File) => Promise<Suite>;
3274
+ clear: () => void;
3275
+ on: <T extends keyof SuiteHooks<ExtraContext>>(name: T, ...fn: SuiteHooks<ExtraContext>[T]) => void;
3276
+ }
3277
+ type SuiteFactory<ExtraContext = object> = (test: TestAPI<ExtraContext>) => Awaitable<void>;
3278
+ /**
3279
+ * User's custom test context.
3280
+ */
3281
+ interface TestContext {
3282
+ /**
3283
+ * Metadata of the current test
3284
+ */
3285
+ readonly task: Readonly<Test>;
3286
+ /**
3287
+ * An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that will be aborted if the test times out or
3288
+ * the test run was cancelled.
3289
+ * @see {@link https://vitest.dev/guide/test-context#signal}
3290
+ */
3291
+ readonly signal: AbortSignal;
3292
+ /**
3293
+ * Register a callback to run when this specific test fails.
3294
+ * Useful when tests run concurrently.
3295
+ * @see {@link https://vitest.dev/guide/test-context#ontestfailed}
3296
+ */
3297
+ readonly onTestFailed: (fn: OnTestFailedHandler, timeout?: number) => void;
3298
+ /**
3299
+ * Register a callback to run when this specific test finishes.
3300
+ * Useful when tests run concurrently.
3301
+ * @see {@link https://vitest.dev/guide/test-context#ontestfinished}
3302
+ */
3303
+ readonly onTestFinished: (fn: OnTestFinishedHandler, timeout?: number) => void;
3304
+ /**
3305
+ * Mark tests as skipped. All execution after this call will be skipped.
3306
+ * This function throws an error, so make sure you are not catching it accidentally.
3307
+ * @see {@link https://vitest.dev/guide/test-context#skip}
3308
+ */
3309
+ readonly skip: {
3310
+ (note?: string): never;
3311
+ (condition: boolean, note?: string): void;
3312
+ };
3313
+ /**
3314
+ * Add a test annotation that will be displayed by your reporter.
3315
+ * @see {@link https://vitest.dev/guide/test-context#annotate}
3316
+ */
3317
+ readonly annotate: {
3318
+ (message: string, type?: string, attachment?: TestAttachment): Promise<TestAnnotation>;
3319
+ (message: string, attachment?: TestAttachment): Promise<TestAnnotation>;
3320
+ };
3321
+ /**
3322
+ * `expect` instance bound to the current test.
3323
+ *
3324
+ * This API is useful for running snapshot tests concurrently because global expect cannot track them.
3325
+ */
3326
+ readonly expect: ExpectStatic;
3327
+ /**
3328
+ * Create a benchmark to run. It will be reported after the test is finished.
3329
+ * @see {@link https://vitest.dev/guide/benchmarking}
3330
+ */
3331
+ readonly bench: Bench;
3332
+ }
3333
+ type OnTestFailedHandler = (context: TestContext) => Awaitable<void>;
3334
+ type OnTestFinishedHandler = (context: TestContext) => Awaitable<void>;
3335
+ interface TaskHook<HookListener> {
3336
+ (fn: HookListener, timeout?: number): void;
3337
+ }
3338
+ type SequenceHooks = "stack" | "list" | "parallel";
3339
+ type SequenceSetupFiles = "list" | "parallel";
3340
+ /**
3341
+ * Represents a file or data attachment associated with a test artifact.
3342
+ *
3343
+ * Attachments can be either path-based (via `path`) or inline content (via `body`).
3344
+ * The `contentType` helps consumers understand how to interpret the attachment data.
3345
+ */
3346
+ interface TestAttachment {
3347
+ /** MIME type of the attachment (e.g., 'image/png', 'text/plain') */
3348
+ contentType?: string;
3349
+ /** Local file path or external HTTP(S) URL to the attachment. Relative paths are resolved from the project root. */
3350
+ path?: string;
3351
+ /** Inline attachment content as a string or raw binary data */
3352
+ body?: string | Uint8Array | undefined;
3353
+ /**
3354
+ * @experimental
3355
+ * How the string `body` is encoded.
3356
+ * - `'base64'` (default): body is already base64-encoded
3357
+ * - `'utf-8'`: body is a utf8 string
3358
+ *
3359
+ * `body: Uint8Array` is always auto-encoded to string with `bodyEncoding: 'base64'`
3360
+ * regardless of this option.
3361
+ */
3362
+ bodyEncoding?: "base64" | "utf-8";
3363
+ }
3364
+ interface Location {
3365
+ /** Line number in the source file (1-indexed) */
3366
+ line: number;
3367
+ /** Column number in the line (1-indexed) */
3368
+ column: number;
3369
+ }
3370
+ interface FileLocation extends Location {
3371
+ /** Line number in the source file (1-indexed) */
3372
+ line: number;
3373
+ /** Column number in the line (1-indexed) */
3374
+ column: number;
3375
+ /** Path to the source file */
3376
+ file: string;
3377
+ }
3378
+ /**
3379
+ * Source code location information for a test artifact.
3380
+ *
3381
+ * Indicates where in the source code the artifact originated from.
3382
+ */
3383
+ interface TestArtifactLocation extends FileLocation {}
3384
+ /**
3385
+ * @experimental
3386
+ *
3387
+ * Base interface for all test artifacts.
3388
+ *
3389
+ * 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.
3390
+ *
3391
+ * **Important**: when running with [`api.allowWrite`](https://vitest.dev/config/api#api-allowwrite) disabled, Vitest empties the `attachments` array on every artifact before reporting it.
3392
+ */
3393
+ interface TestArtifactBase {
3394
+ /** File or data attachments associated with this artifact */
3395
+ attachments?: TestAttachment[];
3396
+ /** Source location where this artifact was created */
3397
+ location?: TestArtifactLocation;
3398
+ }
3399
+ /**
3400
+ * @deprecated Use {@linkcode TestArtifactLocation} instead.
3401
+ *
3402
+ * Kept for backwards compatibility.
3403
+ */
3404
+ type TestAnnotationLocation = TestArtifactLocation;
3405
+ interface TestAnnotation {
3406
+ message: string;
3407
+ type: string;
3408
+ location?: TestArtifactLocation;
3409
+ attachment?: TestAttachment;
3410
+ }
3411
+ /**
3412
+ * @experimental
3413
+ *
3414
+ * Artifact type for test annotations.
3415
+ */
3416
+ interface TestAnnotationArtifact extends TestArtifactBase {
3417
+ type: "internal:annotation";
3418
+ annotation: TestAnnotation;
3419
+ }
3420
+ interface VisualRegressionArtifactAttachment extends TestAttachment {
3421
+ name: "reference" | "actual" | "diff";
3422
+ width: number;
3423
+ height: number;
3424
+ }
3425
+ /**
3426
+ * @experimental
3427
+ *
3428
+ * Artifact type for visual regressions.
3429
+ */
3430
+ interface VisualRegressionArtifact extends TestArtifactBase {
3431
+ type: "internal:toMatchScreenshot";
3432
+ kind: "visual-regression";
3433
+ message: string;
3434
+ attachments: VisualRegressionArtifactAttachment[];
3435
+ }
3436
+ /**
3437
+ * @experimental
3438
+ */
3439
+ interface BrowserTraceArtifact extends TestArtifactBase {
3440
+ type: "internal:browserTrace";
3441
+ data: unknown;
3442
+ }
3443
+ interface FailureScreenshotArtifactAttachment extends TestAttachment {
3444
+ path: string;
3445
+ /** Original file system path to the screenshot, before attachment resolution */
3446
+ originalPath: string;
3447
+ body?: undefined;
3448
+ }
3449
+ /**
3450
+ * @experimental
3451
+ *
3452
+ * Artifact type for failure screenshots.
3453
+ */
3454
+ interface FailureScreenshotArtifact extends TestArtifactBase {
3455
+ type: "internal:failureScreenshot";
3456
+ attachments: [FailureScreenshotArtifactAttachment] | [];
3457
+ /** The zero-based retry index of the attempt that took the screenshot. */
3458
+ retryIndex?: number;
3459
+ /** The zero-based repeat index of the attempt that took the screenshot. */
3460
+ repeatIndex?: number;
3461
+ }
3462
+ /**
3463
+ * @experimental
3464
+ * @advanced
3465
+ *
3466
+ * Registry for custom test artifact types.
3467
+ *
3468
+ * Augment this interface to register custom artifact types that your tests can produce.
3469
+ *
3470
+ * Each custom artifact should extend {@linkcode TestArtifactBase} and include a unique `type` discriminator property.
3471
+ *
3472
+ * @remarks
3473
+ * - Use a `Symbol` as the **registry key** to guarantee uniqueness
3474
+ * - The `type` property should follow the pattern `'package-name:artifact-name'`, `'internal:'` is a reserved prefix
3475
+ * - Use `attachments` to include files or data; extend {@linkcode TestAttachment} for custom metadata
3476
+ * - `location` property is automatically injected to indicate where the artifact was created
3477
+ *
3478
+ * @example
3479
+ * ```ts
3480
+ * // Define custom attachment type for generated PDF
3481
+ * interface PDFAttachment extends TestAttachment {
3482
+ * contentType: 'application/pdf'
3483
+ * body: Uint8Array
3484
+ * pageCount: number
3485
+ * fileSize: number
3486
+ * }
3487
+ *
3488
+ * interface PDFGenerationArtifact extends TestArtifactBase {
3489
+ * type: 'my-plugin:pdf-generation'
3490
+ * templateName: string
3491
+ * isValid: boolean
3492
+ * attachments: [PDFAttachment]
3493
+ * }
3494
+ *
3495
+ * // Use a symbol to guarantee key uniqueness
3496
+ * const pdfKey = Symbol('pdf-generation')
3497
+ *
3498
+ * declare module 'vitest' {
3499
+ * interface TestArtifactRegistry {
3500
+ * [pdfKey]: PDFGenerationArtifact
3501
+ * }
3502
+ * }
3503
+ *
3504
+ * // Custom assertion for PDF generation
3505
+ * async function toGenerateValidPDF(
3506
+ * this: MatcherState,
3507
+ * actual: PDFTemplate,
3508
+ * data: Record<string, unknown>
3509
+ * ): AsyncExpectationResult {
3510
+ * const pdfBuffer = await actual.render(data)
3511
+ * const validation = await validatePDF(pdfBuffer)
3512
+ *
3513
+ * await recordArtifact(this.task, {
3514
+ * type: 'my-plugin:pdf-generation',
3515
+ * templateName: actual.name,
3516
+ * isValid: validation.success,
3517
+ * attachments: [{
3518
+ * contentType: 'application/pdf',
3519
+ * body: pdfBuffer,
3520
+ * pageCount: validation.pageCount,
3521
+ * fileSize: pdfBuffer.byteLength
3522
+ * }]
3523
+ * })
3524
+ *
3525
+ * return {
3526
+ * pass: validation.success,
3527
+ * message: () => validation.success
3528
+ * ? `Generated valid PDF with ${validation.pageCount} pages`
3529
+ * : `Invalid PDF: ${validation.error}`
3530
+ * }
3531
+ * }
3532
+ * ```
3533
+ */
3534
+ interface TestArtifactRegistry {}
3535
+ /**
3536
+ * @experimental
3537
+ *
3538
+ * Union type of all test artifacts, including built-in and custom registered artifacts.
3539
+ *
3540
+ * This type automatically includes all artifacts registered via {@link TestArtifactRegistry}.
3541
+ */
3542
+ type TestArtifact = BrowserTraceArtifact | FailureScreenshotArtifact | TestAnnotationArtifact | VisualRegressionArtifact | TestArtifactRegistry[keyof TestArtifactRegistry];
3543
+ /**
3544
+ * Possible options to run a single file in a test.
3545
+ */
3546
+ interface FileSpecification {
3547
+ filepath: string;
3548
+ fileTags?: string[];
3549
+ testLocations?: number[] | undefined;
3550
+ testNamePattern?: RegExp | undefined;
3551
+ testTagsFilter?: string[] | undefined;
3552
+ testIds?: string[] | undefined;
3553
+ testNames?: string[] | undefined;
3554
+ }
3555
+ type VitestRunnerImportSource = "collect" | "setup";
3556
+ type CancelReason = "keyboard-input" | "test-failure" | (string & Record<string, never>);
3557
+ interface TestTryOptions {
3558
+ retry: number;
3559
+ repeats: number;
3560
+ }
3561
+ interface VitestRunner {
3562
+ /**
3563
+ * First thing that's getting called before actually collecting and running tests.
3564
+ */
3565
+ onBeforeCollect?: (paths: string[]) => unknown;
3566
+ /**
3567
+ * Called after the file task was created but not collected yet.
3568
+ */
3569
+ onCollectStart?: (file: File) => unknown;
3570
+ /**
3571
+ * Called after collecting tests and before "onBeforeRun".
3572
+ */
3573
+ onCollected?: (files: File[]) => unknown;
3574
+ /**
3575
+ * Called when test runner should cancel next test runs.
3576
+ * Runner should listen for this method and mark tests and suites as skipped in
3577
+ * "onBeforeRunSuite" and "onBeforeRunTask" when called.
3578
+ */
3579
+ cancel?: (reason: CancelReason) => unknown;
3580
+ /**
3581
+ * Called before running a single test. Doesn't have "result" yet.
3582
+ */
3583
+ onBeforeRunTask?: (test: Test) => unknown;
3584
+ /**
3585
+ * Called before actually running the test function. Already has "result" with "state" and "startTime".
3586
+ */
3587
+ onBeforeTryTask?: (test: Test, options: TestTryOptions) => unknown;
3588
+ /**
3589
+ * When the task has finished running, but before cleanup hooks are called
3590
+ */
3591
+ onTaskFinished?: (test: Test) => unknown;
3592
+ /**
3593
+ * Called after result and state are set.
3594
+ */
3595
+ onAfterRunTask?: (test: Test) => unknown;
3596
+ /**
3597
+ * Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws.
3598
+ */
3599
+ onAfterTryTask?: (test: Test, options: TestTryOptions) => unknown;
3600
+ /**
3601
+ * Called after the retry resolution happened. Unlike `onAfterTryTask`, the test now has a new state.
3602
+ * All `after` hooks were also called by this point.
3603
+ */
3604
+ onAfterRetryTask?: (test: Test, options: TestTryOptions) => unknown;
3605
+ /**
3606
+ * Called before running a single suite. Doesn't have "result" yet.
3607
+ */
3608
+ onBeforeRunSuite?: (suite: Suite) => unknown;
3609
+ /**
3610
+ * Called after running a single suite. Has state and result.
3611
+ */
3612
+ onAfterRunSuite?: (suite: Suite) => unknown;
3613
+ /**
3614
+ * If defined, will be called instead of usual Vitest suite partition and handling.
3615
+ * "before" and "after" hooks will not be ignored.
3616
+ */
3617
+ runSuite?: (suite: Suite) => Promise<void>;
3618
+ /**
3619
+ * If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function.
3620
+ * "before" and "after" hooks will not be ignored.
3621
+ */
3622
+ runTask?: (test: Test) => Promise<void>;
3623
+ /**
3624
+ * Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests.
3625
+ */
3626
+ onTaskUpdate?: (task: TaskResultPack[], events: TaskEventPack[]) => Promise<void>;
3627
+ /**
3628
+ * Called when annotation is added via the `context.annotate` method.
3629
+ */
3630
+ onTestAnnotate?: (test: Test, annotation: TestAnnotation) => Promise<TestAnnotation>;
3631
+ /**
3632
+ * @experimental
3633
+ *
3634
+ * Called when artifacts are recorded on tests via the `recordArtifact` utility.
3635
+ */
3636
+ onTestArtifactRecord?: <Artifact extends TestArtifact>(test: Test, artifact: Artifact) => Promise<Artifact>;
3637
+ /**
3638
+ * Called before running all tests in collected paths.
3639
+ */
3640
+ onBeforeRunFiles?: (files: File[]) => unknown;
3641
+ /**
3642
+ * Called right after running all tests in collected paths.
3643
+ */
3644
+ onAfterRunFiles?: (files: File[]) => unknown;
3645
+ /**
3646
+ * Called when new context for a test is defined. Useful if you want to add custom properties to the context.
3647
+ * If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead.
3648
+ *
3649
+ * @see https://vitest.dev/advanced/runner#your-task-function
3650
+ */
3651
+ extendTaskContext?: (context: TestContext) => TestContext;
3652
+ /**
3653
+ * Called when test and setup files are imported. Can be called in two situations: when collecting tests and when importing setup files.
3654
+ */
3655
+ importFile: (filepath: string, source: VitestRunnerImportSource) => unknown;
3656
+ /**
3657
+ * Function that is called when the runner attempts to get the value when `test.extend` is used with `{ injected: true }`
3658
+ */
3659
+ injectValue?: (key: string) => unknown;
3660
+ /**
3661
+ * Gets the time spent importing each individual non-externalized file that Vitest collected.
3662
+ */
3663
+ getImportDurations?: () => Record<string, ImportDuration>;
3664
+ /**
3665
+ * Gets the cumulative time the worker has spent waiting for the server to
3666
+ * resolve and transform modules. Used to attribute the transform wait to the
3667
+ * setup and collect phases.
3668
+ */
3669
+ getModuleFetchDuration?: () => number;
3670
+ /**
3671
+ * Publicly available configuration.
3672
+ */
3673
+ config: SerializedConfig;
3674
+ /**
3675
+ * The name of the current pool. Can affect how stack trace is inferred on the server side.
3676
+ */
3677
+ pool?: string;
3678
+ /**
3679
+ * The current Vite environment that processes the files on the server.
3680
+ */
3681
+ viteEnvironment?: string;
3682
+ onCleanupWorkerContext?: (cleanup: () => unknown) => void;
3683
+ trace?<T>(name: string, cb: () => T): T;
3684
+ trace?<T>(name: string, attributes: Record<string, any>, cb: () => T): T;
3685
+ }
3686
+
3687
+ /**
3688
+ * Config that tests have access to.
3689
+ */
3690
+ interface SerializedConfig {
3691
+ root: string;
3692
+ setupFiles: string[];
3693
+ name: string | undefined;
3694
+ passWithNoTests: boolean;
3695
+ testNamePattern: RegExp | undefined;
3696
+ allowOnly: boolean;
3697
+ sequence: {
3698
+ shuffle?: boolean;
3699
+ concurrent?: boolean;
3700
+ seed: number;
3701
+ hooks: SequenceHooks;
3702
+ setupFiles: SequenceSetupFiles;
3703
+ };
3704
+ maxConcurrency: number;
3705
+ testTimeout: number;
3706
+ hookTimeout: number;
3707
+ retry: SerializableRetry;
3708
+ repeats?: number;
3709
+ includeTaskLocation: boolean | undefined;
3710
+ tags: TestTagDefinition[];
3711
+ tagsFilter: string[] | undefined;
3712
+ strictTags: boolean;
3713
+ color?: LabelColor;
3714
+ globals: boolean;
3715
+ injectCjsGlobals: boolean;
3716
+ base: string | undefined;
3717
+ snapshotEnvironment?: string;
3718
+ disableConsoleIntercept: boolean | undefined;
3719
+ runner: string | undefined;
3720
+ isolate: boolean;
3721
+ maxWorkers: number;
3722
+ bail: number | undefined;
3723
+ environmentOptions?: Record<string, any>;
3724
+ clearMocks: boolean;
3725
+ mockReset: boolean;
3726
+ restoreMocks: boolean;
3727
+ unstubGlobals: boolean;
3728
+ unstubEnvs: boolean;
3729
+ fakeTimers: FakeTimersConfig;
3730
+ defines: Record<string, any>;
3731
+ expect: {
3732
+ requireAssertions?: boolean;
3733
+ poll?: {
3734
+ timeout?: number;
3735
+ interval?: number;
3736
+ };
3737
+ };
3738
+ printConsoleTrace: boolean | undefined;
3739
+ deps: {
3740
+ web: {
3741
+ transformAssets?: boolean;
3742
+ transformCss?: boolean;
3743
+ transformGlobPattern?: RegExp | RegExp[];
3744
+ };
3745
+ optimizer: Record<string, {
3746
+ enabled: boolean;
3747
+ }>;
3748
+ interopDefault: boolean | undefined;
3749
+ moduleDirectories: string[] | undefined;
3750
+ };
3751
+ snapshotOptions: {
3752
+ updateSnapshot: SnapshotUpdateState;
3753
+ expand: boolean | undefined;
3754
+ snapshotFormat: PrettyFormatOptions | undefined;
3755
+ /**
3756
+ * only exists for tests, not available in the main process
3757
+ */
3758
+ snapshotEnvironment: SnapshotEnvironment;
3759
+ };
3760
+ pool: string;
3761
+ snapshotSerializers: string[];
3762
+ chaiConfig: {
3763
+ includeStack?: boolean;
3764
+ showDiff?: boolean;
3765
+ truncateThreshold?: number;
3766
+ } | undefined;
3767
+ taskTitleValueFormatTruncate: number;
3768
+ api: {
3769
+ allowExec: boolean | undefined;
3770
+ allowWrite: boolean | undefined;
3771
+ };
3772
+ diff: string | SerializedDiffOptions | undefined;
3773
+ inspect: boolean | string | undefined;
3774
+ inspectBrk: boolean | string | undefined;
3775
+ inspector: {
3776
+ enabled?: boolean;
3777
+ port?: number;
3778
+ host?: string;
3779
+ waitForDebugger?: boolean;
3780
+ };
3781
+ watch: boolean;
3782
+ env: Record<string, any>;
3783
+ browser: {
3784
+ name: string;
3785
+ headless: boolean;
3786
+ ui: boolean;
3787
+ viewport: {
3788
+ width: number;
3789
+ height: number;
3790
+ };
3791
+ locators: {
3792
+ testIdAttribute: string;
3793
+ exact: boolean;
3794
+ errorFormat: "html" | "aria" | "all";
3795
+ };
3796
+ screenshotFailures: boolean;
3797
+ providerOptions: {
3798
+ actionTimeout?: number;
3799
+ };
3800
+ trace: BrowserTraceViewMode;
3801
+ traceView: {
3802
+ enabled: boolean;
3803
+ mode: BrowserTraceViewRecordingMode;
3804
+ recordCanvas: boolean;
3805
+ inlineImages: boolean;
3806
+ ariaSnapshot: boolean;
3807
+ };
3808
+ trackUnhandledErrors: boolean;
3809
+ importMapMocks: boolean | undefined;
3810
+ detailsPanelPosition: "right" | "bottom";
3811
+ };
3812
+ standalone: boolean;
3813
+ logHeapUsage: boolean | undefined;
3814
+ detectAsyncLeaks: boolean;
3815
+ coverage: SerializedCoverageConfig;
3816
+ benchmark: {
3817
+ enabled: boolean;
3818
+ retainSamples: boolean;
3819
+ provider: string | undefined;
3820
+ suppressExportGetterWarnings: boolean;
3821
+ projectName: string;
3822
+ };
3823
+ serializedDefines: string;
3824
+ fsModuleCache: boolean;
3825
+ experimental: {
3826
+ importDurations: {
3827
+ print: boolean | "on-warn";
3828
+ limit: number;
3829
+ failOnDanger: boolean;
3830
+ thresholds: {
3831
+ warn: number;
3832
+ danger: number;
3833
+ };
3834
+ };
3835
+ viteModuleRunner: boolean;
3836
+ nodeLoader: boolean;
3837
+ recordDependencies: boolean;
3838
+ traceTimeline: boolean;
3839
+ openTelemetry: {
3840
+ enabled: boolean;
3841
+ sdkPath?: string;
3842
+ browserSdkPath?: string;
3843
+ } | undefined;
3844
+ };
3845
+ mergeReportsLabel: string | undefined;
3846
+ slowTestThreshold: number | undefined;
3847
+ disableColors: boolean;
3848
+ attachmentsDir: string;
3849
+ }
3850
+ interface SerializedCoverageConfig {
3851
+ provider: "istanbul" | "v8" | "custom" | undefined;
3852
+ reportsDirectory: string;
3853
+ /** Directory where workers write raw coverage results, shard-aware */
3854
+ coverageFilesDirectory: string;
3855
+ htmlDir: string | undefined;
3856
+ enabled: boolean;
3857
+ customProviderModule: string | undefined;
3858
+ autoAttachSubprocess: boolean;
3859
+ }
3860
+ interface SerializedRootConfig extends SerializedConfig {
3861
+ projects: SerializedConfig[];
3862
+ }
3863
+ type RuntimeConfig = Pick<SerializedConfig, "allowOnly" | "testTimeout" | "hookTimeout" | "clearMocks" | "mockReset" | "restoreMocks" | "fakeTimers" | "maxConcurrency" | "expect" | "printConsoleTrace"> & {
3864
+ sequence?: {
3865
+ hooks?: SequenceHooks;
3866
+ };
3867
+ };
3868
+ type RuntimeOptions = Partial<RuntimeConfig>;
3869
+ type BrowserTraceViewRecordingMode = "off" | "on" | "failure-only";
3870
+ type BrowserTraceViewMode = "on" | "off" | "on-first-retry" | "on-all-retries" | "retain-on-failure";
3871
+
3872
+ export { fn as B, _vitest_spy as _, createChainable as a2, afterAll as b9, afterEach as ba, aroundAll as bb, aroundEach as bc, beforeAll as bd, beforeEach as be, onTestFailed as bf, onTestFinished as bg, disableDefaultColors as bj, SnapshotState as bq, format as f, inspect as i, stringify as s, spyOn as z };
3873
+ export type { TestTryOptions as $, Awaitable as A, MaybeMockedDeep as C, DiffOptions as D, ExpectStatic as E, FileSpecification as F, MaybeMocked as G, MaybePartiallyMocked as H, MaybePartiallyMockedDeep as I, MockInstance as J, TestAPI as K, LabelColor as L, ModuleGraphData as M, SuiteCollector as N, SuiteAPI as O, ParsedStack as P, Suite as Q, RuntimeOptions as R, SerializedCoverageConfig as S, TestError as T, UserConsoleLog as U, VitestRunner as V, SuiteHooks as W, VitestRunnerImportSource as X, Task as Y, CancelReason as Z, File as a, TestArtifactLocation as a$, TestContext as a0, ImportDuration as a1, AfterSuiteRunMeta as a3, Assertion as a4, AsymmetricMatchersContaining as a5, BaselineData as a6, Bench as a7, BenchFn as a8, BenchFnOptions as a9, Mocked as aA, MockedClass as aB, MockedFunction as aC, MockedObject as aD, OnTestFailedHandler as aE, OnTestFinishedHandler as aF, RunMode as aG, TaskBase as aH, TaskResult as aI, TaskResultAttempt as aJ, RuntimeConfig as aK, SerializedError as aL, SnapshotData as aM, SnapshotMatchOptions as aN, SnapshotResult as aO, SnapshotSerializer as aP, SnapshotStateOptions as aQ, SnapshotSummary as aR, SnapshotUpdateState as aS, SuiteFactory as aT, SuiteOptions as aU, TaskCustomOptions as aV, TaskMeta as aW, TaskState as aX, TestAnnotationArtifact as aY, TestAnnotationLocation as aZ, TestArtifactBase as a_, BenchFromSource as aa, BenchOptions as ab, BenchRegistration as ac, BenchRegistrationInput as ad, BenchResult as ae, BenchRunOptions as af, BenchStorage as ag, BenchmarkGroup as ah, BenchmarkProvider as ai, BrowserTraceArtifact as aj, DeeplyAllowMatchers as ak, DomainMatchResult as al, FailureScreenshotArtifact as am, JestAssertion as an, RawMatcherFn as ao, Matchers as ap, MatchersObject as aq, MockContext as ar, MockResult as as, MockResultIncomplete as at, MockResultReturn as au, MockResultThrow as av, MockSettledResult as aw, MockSettledResultFulfilled as ax, MockSettledResultIncomplete as ay, MockSettledResultRejected as az, SerializedConfig as b, TestArtifactRegistry as b0, TestAttachment as b1, TestBenchmark as b2, TestBenchmarkTask as b3, TestFunction as b4, TestOptions as b5, TestTags as b6, UncheckedSnapshot as b7, VisualRegressionArtifact as b8, SequenceHooks as bh, SequenceSetupFiles as bi, SerializableRetry as bk, BrowserTraceViewMode as bl, BrowserTraceViewRecordingMode as bm, Arrayable as bn, AsyncLeak as bo, PrettyFormatOptions as bp, PromisifyAssertion as br, Tester as bs, Plugin as bt, SnapshotEnvironment as bu, SnapshotEnvironmentOptions as bv, FetchCachedFileSystemResult as bw, ResolveFunctionResult as bx, SerializedDiffOptions as c, StringifyOptions as d, FakeTimersConfig as e, TestTagDefinition as g, TestAnnotation as h, TestArtifact as j, TaskResultPack as k, TaskEventPack as l, SerializedRootConfig as m, Test as n, TaskPopulated as o, ProvidedContext as p, MatcherState as q, SyncExpectationResult as r, AsyncExpectationResult as t, DomainSnapshotAdapter as u, ExpectationResult as v, Procedure as w, Mock as x, TemporalTimelike as y };