vitest 0.20.2 → 0.21.1

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 (35) hide show
  1. package/LICENSE.md +29 -0
  2. package/dist/browser.d.ts +9 -1887
  3. package/dist/browser.mjs +7 -7
  4. package/dist/{chunk-api-setup.7c4c8879.mjs → chunk-api-setup.7a6ba7fb.mjs} +5 -5
  5. package/dist/{chunk-constants.16825f0c.mjs → chunk-constants.26dc9f85.mjs} +1 -1
  6. package/dist/{chunk-defaults.1c51d585.mjs → chunk-defaults.02abff90.mjs} +2 -2
  7. package/dist/{chunk-integrations-globals.56a11010.mjs → chunk-integrations-globals.44a8f047.mjs} +6 -6
  8. package/dist/{chunk-mock-date.9160e13b.mjs → chunk-mock-date.bc81a3ac.mjs} +11 -8
  9. package/dist/{chunk-node-git.43dbdd42.mjs → chunk-node-git.c2be9c49.mjs} +1 -1
  10. package/dist/{chunk-runtime-chain.b6c2cdbc.mjs → chunk-runtime-chain.98d42d89.mjs} +30 -21
  11. package/dist/{chunk-runtime-error.0aa0dc06.mjs → chunk-runtime-error.87a2b5a2.mjs} +12 -11
  12. package/dist/{chunk-runtime-hooks.3ee34848.mjs → chunk-runtime-hooks.453f8858.mjs} +4 -4
  13. package/dist/{chunk-runtime-mocker.0a8f7c5e.mjs → chunk-runtime-mocker.23b62bfa.mjs} +34 -12
  14. package/dist/{chunk-runtime-rpc.dbf0b31d.mjs → chunk-runtime-rpc.b50ab560.mjs} +1 -1
  15. package/dist/{chunk-utils-source-map.8198ebd9.mjs → chunk-utils-source-map.94107ee8.mjs} +1 -1
  16. package/dist/{chunk-vite-node-client.a247c2c2.mjs → chunk-vite-node-client.fdd9592c.mjs} +7 -3
  17. package/dist/{chunk-vite-node-debug.c5887932.mjs → chunk-vite-node-debug.09afb76f.mjs} +1 -1
  18. package/dist/{chunk-vite-node-externalize.45323563.mjs → chunk-vite-node-externalize.27aee038.mjs} +34 -18
  19. package/dist/chunk-vite-node-utils.f34df9d3.mjs +6887 -0
  20. package/dist/cli.mjs +8 -8
  21. package/dist/config.d.ts +2 -67
  22. package/dist/entry.mjs +7 -7
  23. package/dist/global-60f880c6.d.ts +1779 -0
  24. package/dist/index-4a906fa4.d.ts +164 -0
  25. package/dist/index.d.ts +29 -1903
  26. package/dist/index.mjs +5 -5
  27. package/dist/loader.mjs +73 -17
  28. package/dist/mocker-5e2a8e41.d.ts +3 -0
  29. package/dist/node.d.ts +7 -1667
  30. package/dist/node.mjs +9 -9
  31. package/dist/suite.mjs +4 -4
  32. package/dist/{vendor-index.de788b6a.mjs → vendor-index.ae96af6e.mjs} +14 -14
  33. package/dist/worker.mjs +6 -6
  34. package/package.json +11 -11
  35. package/dist/chunk-vite-node-utils.9dfd1e3f.mjs +0 -1114
package/dist/index.d.ts CHANGED
@@ -1,1905 +1,15 @@
1
- import { ViteDevServer, TransformResult, CommonServerOptions, AliasOptions } from 'vite';
2
- import { Stats } from 'fs';
3
- import { SpyImpl } from 'tinyspy';
4
- import { MessagePort } from 'worker_threads';
1
+ import { s as spyOn, f as fn, M as MaybeMockedDeep, a as MaybeMocked, b as MaybePartiallyMocked, c as MaybePartiallyMockedDeep, E as EnhancedSpy } from './index-4a906fa4.js';
2
+ export { E as EnhancedSpy, q as Mock, r as MockContext, p as MockInstance, u as Mocked, v as MockedClass, n as MockedFunction, o as MockedObject, R as ResolveIdFunction, S as SpyInstance, W as WorkerContext, x as WorkerGlobalState, w as WorkerRPC, h as afterAll, k as afterEach, g as beforeAll, j as beforeEach, m as createExpect, e as describe, l as expect, i as it, d as suite, t as test } from './index-4a906fa4.js';
3
+ import { D as DoneCallback, F as FakeTimerInstallOpts, a as File, T as TaskResultPack, R as ResolvedConfig, M as ModuleGraphData, b as Reporter } from './global-60f880c6.js';
4
+ export { A as ApiConfig, C as ArgumentsType, z as Arrayable, y as Awaitable, B as BuiltinEnvironment, a0 as C8Options, O as Constructable, $ as CoverageReporter, K as DeepMerge, D as DoneCallback, W as Environment, E as EnvironmentOptions, Q as EnvironmentReturn, _ as ErrorWithDiff, a as File, l as HookCleanupCallback, H as HookListener, I as InlineConfig, J as JSDOMOptions, G as MergeInsertions, P as ModuleCache, M as ModuleGraphData, L as MutableArray, N as Nullable, Z as ParsedStack, Y as Position, b as Reporter, a1 as ResolvedC8Options, R as ResolvedConfig, c as RunMode, p as RuntimeContext, r as SnapshotData, u as SnapshotMatchOptions, v as SnapshotResult, t as SnapshotStateOptions, x as SnapshotSummary, s as SnapshotUpdateState, S as Suite, k as SuiteAPI, n as SuiteCollector, o as SuiteFactory, m as SuiteHooks, h as Task, e as TaskBase, f as TaskResult, T as TaskResultPack, d as TaskState, g as Test, j as TestAPI, q as TestContext, i as TestFunction, w as UncheckedSnapshot, U as UserConfig, X as UserConsoleLog, V as Vitest } from './global-60f880c6.js';
5
+ import { TransformResult } from 'vite';
5
6
  import * as chai from 'chai';
6
7
  export { chai };
7
8
  export { assert, should } from 'chai';
8
-
9
- /**
10
- * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
11
- *
12
- * This source code is licensed under the MIT license found in the
13
- * LICENSE file in the root directory of this source tree.
14
- */
15
- declare type Colors = {
16
- comment: {
17
- close: string;
18
- open: string;
19
- };
20
- content: {
21
- close: string;
22
- open: string;
23
- };
24
- prop: {
25
- close: string;
26
- open: string;
27
- };
28
- tag: {
29
- close: string;
30
- open: string;
31
- };
32
- value: {
33
- close: string;
34
- open: string;
35
- };
36
- };
37
- declare type Indent = (arg0: string) => string;
38
- declare type Refs = Array<unknown>;
39
- declare type Print = (arg0: unknown) => string;
40
- declare type ThemeReceived = {
41
- comment?: string;
42
- content?: string;
43
- prop?: string;
44
- tag?: string;
45
- value?: string;
46
- };
47
- declare type CompareKeys = ((a: string, b: string) => number) | undefined;
48
- interface PrettyFormatOptions {
49
- callToJSON?: boolean;
50
- compareKeys?: CompareKeys;
51
- escapeRegex?: boolean;
52
- escapeString?: boolean;
53
- highlight?: boolean;
54
- indent?: number;
55
- maxDepth?: number;
56
- min?: boolean;
57
- plugins?: Plugins;
58
- printBasicPrototype?: boolean;
59
- printFunctionName?: boolean;
60
- theme?: ThemeReceived;
61
- }
62
- declare type OptionsReceived = PrettyFormatOptions;
63
- declare type Config = {
64
- callToJSON: boolean;
65
- compareKeys: CompareKeys;
66
- colors: Colors;
67
- escapeRegex: boolean;
68
- escapeString: boolean;
69
- indent: string;
70
- maxDepth: number;
71
- min: boolean;
72
- plugins: Plugins;
73
- printBasicPrototype: boolean;
74
- printFunctionName: boolean;
75
- spacingInner: string;
76
- spacingOuter: string;
77
- };
78
- declare type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string;
79
- declare type Test$1 = (arg0: any) => boolean;
80
- declare type NewPlugin = {
81
- serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string;
82
- test: Test$1;
83
- };
84
- declare type PluginOptions = {
85
- edgeSpacing: string;
86
- min: boolean;
87
- spacing: string;
88
- };
89
- declare type OldPlugin = {
90
- print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string;
91
- test: Test$1;
92
- };
93
- declare type Plugin = NewPlugin | OldPlugin;
94
- declare type Plugins = Array<Plugin>;
95
-
96
- // Type definitions for @sinonjs/fake-timers 8.1
97
- // Project: https://github.com/sinonjs/fake-timers
98
- // Definitions by: Wim Looman <https://github.com/Nemo157>
99
- // Rogier Schouten <https://github.com/rogierschouten>
100
- // Yishai Zehavi <https://github.com/zyishai>
101
- // Remco Haszing <https://github.com/remcohaszing>
102
- // Jaden Simon <https://github.com/JadenSimon>
103
- // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
104
- // TypeScript Version: 2.3
105
-
106
- /**
107
- * Names of clock methods that may be faked by install.
108
- */
109
- type FakeMethod =
110
- | 'setTimeout'
111
- | 'clearTimeout'
112
- | 'setImmediate'
113
- | 'clearImmediate'
114
- | 'setInterval'
115
- | 'clearInterval'
116
- | 'Date'
117
- | 'nextTick'
118
- | 'hrtime'
119
- | 'requestAnimationFrame'
120
- | 'cancelAnimationFrame'
121
- | 'requestIdleCallback'
122
- | 'cancelIdleCallback'
123
- | 'performance'
124
- | 'queueMicrotask';
125
-
126
- interface FakeTimerInstallOpts {
127
- /**
128
- * Installs fake timers with the specified unix epoch (default: 0)
129
- */
130
- now?: number | Date | undefined;
131
-
132
- /**
133
- * An array with names of global methods and APIs to fake. By default, `@sinonjs/fake-timers` does not replace `nextTick()` and `queueMicrotask()`.
134
- * For instance, `FakeTimers.install({ toFake: ['setTimeout', 'nextTick'] })` will fake only `setTimeout()` and `nextTick()`
135
- */
136
- toFake?: FakeMethod[] | undefined;
137
-
138
- /**
139
- * The maximum number of timers that will be run when calling runAll() (default: 1000)
140
- */
141
- loopLimit?: number | undefined;
142
-
143
- /**
144
- * Tells @sinonjs/fake-timers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by
145
- * 20ms for every 20ms change in the real system time) (default: false)
146
- */
147
- shouldAdvanceTime?: boolean | undefined;
148
-
149
- /**
150
- * Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change
151
- * in the real system time (default: 20)
152
- */
153
- advanceTimeDelta?: number | undefined;
154
-
155
- /**
156
- * Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by
157
- * default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. (default: false)
158
- */
159
- shouldClearNativeTimers?: boolean | undefined;
160
- }
161
-
162
- interface UpdatePayload {
163
- type: 'update'
164
- updates: Update[]
165
- }
166
-
167
- interface Update {
168
- type: 'js-update' | 'css-update'
169
- path: string
170
- acceptedPath: string
171
- timestamp: number
172
- }
173
-
174
- interface PrunePayload {
175
- type: 'prune'
176
- paths: string[]
177
- }
178
-
179
- interface FullReloadPayload {
180
- type: 'full-reload'
181
- path?: string
182
- }
183
-
184
- interface ErrorPayload {
185
- type: 'error'
186
- err: {
187
- [name: string]: any
188
- message: string
189
- stack: string
190
- id?: string
191
- frame?: string
192
- plugin?: string
193
- pluginCode?: string
194
- loc?: {
195
- file?: string
196
- line: number
197
- column: number
198
- }
199
- }
200
- }
201
-
202
- interface CustomEventMap {
203
- 'vite:beforeUpdate': UpdatePayload
204
- 'vite:beforePrune': PrunePayload
205
- 'vite:beforeFullReload': FullReloadPayload
206
- 'vite:error': ErrorPayload
207
- }
208
-
209
- type InferCustomEventPayload<T extends string> =
210
- T extends keyof CustomEventMap ? CustomEventMap[T] : any
211
-
212
- interface ViteHotContext {
213
- readonly data: any
214
-
215
- accept(): void
216
- accept(cb: (mod: any) => void): void
217
- accept(dep: string, cb: (mod: any) => void): void
218
- accept(deps: readonly string[], cb: (mods: any[]) => void): void
219
-
220
- /**
221
- * @deprecated
222
- */
223
- acceptDeps(): never
224
-
225
- dispose(cb: (data: any) => void): void
226
- decline(): void
227
- invalidate(): void
228
-
229
- on<T extends string>(
230
- event: T,
231
- cb: (payload: InferCustomEventPayload<T>) => void
232
- ): void
233
- send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void
234
- }
235
- declare class ModuleCacheMap extends Map<string, ModuleCache$1> {
236
- normalizePath(fsPath: string): string;
237
- set(fsPath: string, mod: Partial<ModuleCache$1>): this;
238
- get(fsPath: string): ModuleCache$1 | undefined;
239
- delete(fsPath: string): boolean;
240
- }
241
- declare class ViteNodeRunner {
242
- options: ViteNodeRunnerOptions;
243
- root: string;
244
- debug: boolean;
245
- /**
246
- * Holds the cache of modules
247
- * Keys of the map are filepaths, or plain package names
248
- */
249
- moduleCache: ModuleCacheMap;
250
- constructor(options: ViteNodeRunnerOptions);
251
- executeFile(file: string): Promise<any>;
252
- executeId(id: string): Promise<any>;
253
- /** @internal */
254
- cachedRequest(rawId: string, callstack: string[]): Promise<any>;
255
- /** @internal */
256
- directRequest(id: string, fsPath: string, _callstack: string[]): Promise<any>;
257
- prepareContext(context: Record<string, any>): Record<string, any>;
258
- shouldResolveId(dep: string): boolean;
259
- /**
260
- * Define if a module should be interop-ed
261
- * This function mostly for the ability to override by subclass
262
- */
263
- shouldInterop(path: string, mod: any): boolean;
264
- /**
265
- * Import a module and interop it
266
- */
267
- interopedImport(path: string): Promise<any>;
268
- hasNestedDefault(target: any): any;
269
- }
270
- interface DepsHandlingOptions {
271
- external?: (string | RegExp)[];
272
- inline?: (string | RegExp)[] | true;
273
- /**
274
- * Try to guess the CJS version of a package when it's invalid ESM
275
- * @default false
276
- */
277
- fallbackCJS?: boolean;
278
- }
279
- interface StartOfSourceMap {
280
- file?: string;
281
- sourceRoot?: string;
282
- }
283
- interface RawSourceMap extends StartOfSourceMap {
284
- version: string;
285
- sources: string[];
286
- names: string[];
287
- sourcesContent?: string[];
288
- mappings: string;
289
- }
290
- interface FetchResult {
291
- code?: string;
292
- externalize?: string;
293
- map?: RawSourceMap;
294
- }
295
- declare type HotContext = Omit<ViteHotContext, 'acceptDeps' | 'decline'>;
296
- declare type FetchFunction = (id: string) => Promise<FetchResult>;
297
- declare type ResolveIdFunction$1 = (id: string, importer?: string) => Promise<ViteNodeResolveId | null>;
298
- declare type CreateHotContextFunction = (runner: ViteNodeRunner, url: string) => HotContext;
299
- interface ModuleCache$1 {
300
- promise?: Promise<any>;
301
- exports?: any;
302
- code?: string;
303
- }
304
- interface ViteNodeRunnerOptions {
305
- root: string;
306
- fetchModule: FetchFunction;
307
- resolveId?: ResolveIdFunction$1;
308
- createHotContext?: CreateHotContextFunction;
309
- base?: string;
310
- moduleCache?: ModuleCacheMap;
311
- interopDefault?: boolean;
312
- requestStubs?: Record<string, any>;
313
- debug?: boolean;
314
- }
315
- interface ViteNodeResolveId {
316
- external?: boolean | 'absolute' | 'relative';
317
- id: string;
318
- meta?: Record<string, any> | null;
319
- moduleSideEffects?: boolean | 'no-treeshake' | null;
320
- syntheticNamedExports?: boolean | string | null;
321
- }
322
- interface ViteNodeServerOptions {
323
- /**
324
- * Inject inline sourcemap to modules
325
- * @default 'inline'
326
- */
327
- sourcemap?: 'inline' | boolean;
328
- /**
329
- * Deps handling
330
- */
331
- deps?: DepsHandlingOptions;
332
- /**
333
- * Transform method for modules
334
- */
335
- transformMode?: {
336
- ssr?: RegExp[];
337
- web?: RegExp[];
338
- };
339
- debug?: DebuggerOptions;
340
- }
341
- interface DebuggerOptions {
342
- /**
343
- * Dump the transformed module to filesystem
344
- * Passing a string will dump to the specified path
345
- */
346
- dumpModules?: boolean | string;
347
- /**
348
- * Read dumpped module from filesystem whenever exists.
349
- * Useful for debugging by modifying the dump result from the filesystem.
350
- */
351
- loadDumppedModules?: boolean;
352
- }
353
-
354
- declare class Debugger {
355
- options: DebuggerOptions;
356
- dumpDir: string | undefined;
357
- initPromise: Promise<void> | undefined;
358
- externalizeMap: Map<string, string>;
359
- constructor(root: string, options: DebuggerOptions);
360
- clearDump(): Promise<void>;
361
- encodeId(id: string): string;
362
- recordExternalize(id: string, path: string): Promise<void>;
363
- dumpFile(id: string, result: TransformResult | null): Promise<void>;
364
- loadDump(id: string): Promise<TransformResult | null>;
365
- writeInfo(): Promise<void>;
366
- }
367
-
368
- declare class ViteNodeServer {
369
- server: ViteDevServer;
370
- options: ViteNodeServerOptions;
371
- private fetchPromiseMap;
372
- private transformPromiseMap;
373
- fetchCache: Map<string, {
374
- timestamp: number;
375
- result: FetchResult;
376
- }>;
377
- externalizeCache: Map<string, Promise<string | false>>;
378
- debugger?: Debugger;
379
- constructor(server: ViteDevServer, options?: ViteNodeServerOptions);
380
- shouldExternalize(id: string): Promise<string | false>;
381
- resolveId(id: string, importer?: string): Promise<ViteNodeResolveId | null>;
382
- fetchModule(id: string): Promise<FetchResult>;
383
- transformRequest(id: string): Promise<TransformResult | null | undefined>;
384
- getTransformMode(id: string): "web" | "ssr";
385
- private _fetchModule;
386
- private _transformRequest;
387
- }
388
-
389
- declare class SnapshotManager {
390
- options: SnapshotStateOptions;
391
- summary: SnapshotSummary;
392
- extension: string;
393
- constructor(options: SnapshotStateOptions);
394
- clear(): void;
395
- add(result: SnapshotResult): void;
396
- resolvePath(testPath: string): string;
397
- }
398
-
399
- declare type RunWithFiles = (files: string[], invalidates?: string[]) => Promise<void>;
400
- interface WorkerPool {
401
- runTests: RunWithFiles;
402
- close: () => Promise<void>;
403
- }
404
-
405
- interface CollectingPromise {
406
- promise: Promise<void>;
407
- resolve: () => void;
408
- }
409
- declare class StateManager {
410
- filesMap: Map<string, File>;
411
- pathsSet: Set<string>;
412
- collectingPromise: CollectingPromise | undefined;
413
- idMap: Map<string, Task>;
414
- taskFileMap: WeakMap<Task, File>;
415
- errorsSet: Set<unknown>;
416
- catchError(err: unknown, type: string): void;
417
- clearErrors(): void;
418
- getUnhandledErrors(): unknown[];
419
- startCollectingPaths(): void;
420
- finishCollectingPaths(): void;
421
- getPaths(): Promise<string[]>;
422
- getFiles(keys?: string[]): File[];
423
- getFilepaths(): string[];
424
- getFailedFilepaths(): string[];
425
- collectPaths(paths?: string[]): void;
426
- collectFiles(files?: File[]): void;
427
- clearFiles(paths?: string[]): void;
428
- updateId(task: Task): void;
429
- updateTasks(packs: TaskResultPack[]): void;
430
- updateUserLog(log: UserConsoleLog): void;
431
- }
432
-
433
- declare class Logger {
434
- ctx: Vitest;
435
- console: Console;
436
- outputStream: NodeJS.WriteStream & {
437
- fd: 1;
438
- };
439
- errorStream: NodeJS.WriteStream & {
440
- fd: 2;
441
- };
442
- logUpdate: ((...text: string[]) => void) & {
443
- clear(): void;
444
- done(): void;
445
- };
446
- private _clearScreenPending;
447
- constructor(ctx: Vitest, console?: Console);
448
- log(...args: any[]): void;
449
- error(...args: any[]): void;
450
- warn(...args: any[]): void;
451
- clearScreen(message: string, force?: boolean): void;
452
- private _clearScreen;
453
- printError(err: unknown, fullStack?: boolean, type?: string): Promise<void>;
454
- printNoTestFound(filters?: string[]): void;
455
- printBanner(): void;
456
- printUnhandledErrors(errors: unknown[]): Promise<void>;
457
- }
458
-
459
- interface SuiteResultCache {
460
- failed: boolean;
461
- duration: number;
462
- }
463
- declare class ResultsCache {
464
- private cache;
465
- private cachePath;
466
- private version;
467
- private root;
468
- getCachePath(): string | null;
469
- setConfig(root: string, config: ResolvedConfig['cache']): void;
470
- getResults(fsPath: string): SuiteResultCache | undefined;
471
- readFromCache(): Promise<void>;
472
- updateResults(files: File[]): void;
473
- removeFromCache(filepath: string): void;
474
- writeToCache(): Promise<void>;
475
- }
476
-
477
- interface CliOptions extends UserConfig {
478
- /**
479
- * Override the watch mode
480
- */
481
- run?: boolean;
482
- }
483
-
484
- declare type FileStatsCache = Pick<Stats, 'size'>;
485
- declare class FilesStatsCache {
486
- cache: Map<string, FileStatsCache>;
487
- getStats(fsPath: string): FileStatsCache | undefined;
488
- updateStats(fsPath: string): Promise<void>;
489
- removeStats(fsPath: string): void;
490
- }
491
-
492
- declare class VitestCache {
493
- results: ResultsCache;
494
- stats: FilesStatsCache;
495
- getFileTestResults(id: string): SuiteResultCache | undefined;
496
- getFileStats(id: string): {
497
- size: number;
498
- } | undefined;
499
- static resolveCacheDir(root: string, dir: string | undefined): string;
500
- static clearCache(options: CliOptions): Promise<{
501
- dir: string;
502
- cleared: boolean;
503
- }>;
504
- }
505
-
506
- declare class Vitest {
507
- config: ResolvedConfig;
508
- configOverride: Partial<ResolvedConfig> | undefined;
509
- server: ViteDevServer;
510
- state: StateManager;
511
- snapshot: SnapshotManager;
512
- cache: VitestCache;
513
- reporters: Reporter[];
514
- logger: Logger;
515
- pool: WorkerPool | undefined;
516
- vitenode: ViteNodeServer;
517
- invalidates: Set<string>;
518
- changedTests: Set<string>;
519
- runningPromise?: Promise<void>;
520
- closingPromise?: Promise<void>;
521
- isFirstRun: boolean;
522
- restartsCount: number;
523
- runner: ViteNodeRunner;
524
- constructor();
525
- private _onRestartListeners;
526
- setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
527
- getSerializableConfig(): ResolvedConfig;
528
- start(filters?: string[]): Promise<void>;
529
- private getTestDependencies;
530
- filterTestsBySource(tests: string[]): Promise<string[]>;
531
- runFiles(paths: string[]): Promise<void>;
532
- rerunFiles(files?: string[], trigger?: string): Promise<void>;
533
- changeNamePattern(pattern: string, files?: string[], trigger?: string): Promise<void>;
534
- rerunFailed(): Promise<void>;
535
- updateSnapshot(files?: string[]): Promise<void>;
536
- private _rerunTimer;
537
- private scheduleRerun;
538
- private unregisterWatcher;
539
- private registerWatcher;
540
- /**
541
- * @returns A value indicating whether rerun is needed (changedTests was mutated)
542
- */
543
- private handleFileChanged;
544
- close(): Promise<void>;
545
- exit(force?: boolean): Promise<void>;
546
- report<T extends keyof Reporter>(name: T, ...args: ArgumentsType$1<Reporter[T]>): Promise<void>;
547
- globTestFiles(filters?: string[]): Promise<string[]>;
548
- isTargetFile(id: string, source?: string): Promise<boolean>;
549
- isInSourceTestFile(code: string): boolean;
550
- onServerRestarted(fn: () => void): void;
551
- }
552
-
553
- declare type MockMap = Map<string, Record<string, string | null | (() => unknown)>>;
554
-
555
- interface TestSequencer {
556
- /**
557
- * Slicing tests into shards. Will be run before `sort`.
558
- * Only run, if `shard` is defined.
559
- */
560
- shard(files: string[]): Awaitable<string[]>;
561
- sort(files: string[]): Awaitable<string[]>;
562
- }
563
- interface TestSequencerConstructor {
564
- new (ctx: Vitest): TestSequencer;
565
- }
566
-
567
- declare abstract class BaseReporter implements Reporter {
568
- start: number;
569
- end: number;
570
- watchFilters?: string[];
571
- isTTY: false;
572
- ctx: Vitest;
573
- private _filesInWatchMode;
574
- private _lastRunTimeout;
575
- private _lastRunTimer;
576
- private _lastRunCount;
577
- constructor();
578
- onInit(ctx: Vitest): void;
579
- relative(path: string): string;
580
- onFinished(files?: File[], errors?: unknown[]): Promise<void>;
581
- onTaskUpdate(packs: TaskResultPack[]): void;
582
- onWatcherStart(): Promise<void>;
583
- private resetLastRunLog;
584
- onWatcherRerun(files: string[], trigger?: string): Promise<void>;
585
- onUserConsoleLog(log: UserConsoleLog): void;
586
- shouldLog(log: UserConsoleLog): boolean;
587
- onServerRestart(): void;
588
- reportSummary(files: File[]): Promise<void>;
589
- private printTaskErrors;
590
- registerUnhandledRejection(): void;
591
- }
592
-
593
- interface ListRendererOptions {
594
- renderSucceed?: boolean;
595
- logger: Logger;
596
- showHeap: boolean;
597
- }
598
- declare const createListRenderer: (_tasks: Task[], options: ListRendererOptions) => {
599
- start(): any;
600
- update(_tasks: Task[]): any;
601
- stop(): Promise<any>;
602
- clear(): void;
603
- };
604
-
605
- declare class DefaultReporter extends BaseReporter {
606
- renderer?: ReturnType<typeof createListRenderer>;
607
- rendererOptions: ListRendererOptions;
608
- onTestRemoved(trigger?: string): Promise<void>;
609
- onCollected(): void;
610
- onFinished(files?: File[], errors?: unknown[]): Promise<void>;
611
- onWatcherStart(): Promise<void>;
612
- stopListRender(): Promise<void>;
613
- onWatcherRerun(files: string[], trigger?: string): Promise<void>;
614
- onUserConsoleLog(log: UserConsoleLog): void;
615
- }
616
-
617
- declare class DotReporter extends BaseReporter {
618
- renderer?: ReturnType<typeof createListRenderer>;
619
- onCollected(): void;
620
- onFinished(files?: File[], errors?: unknown[]): Promise<void>;
621
- onWatcherStart(): Promise<void>;
622
- stopListRender(): Promise<void>;
623
- onWatcherRerun(files: string[], trigger?: string): Promise<void>;
624
- onUserConsoleLog(log: UserConsoleLog): void;
625
- }
626
-
627
- interface Callsite {
628
- line: number;
629
- column: number;
630
- }
631
- declare class JsonReporter implements Reporter {
632
- start: number;
633
- ctx: Vitest;
634
- onInit(ctx: Vitest): void;
635
- protected logTasks(files: File[]): Promise<void>;
636
- onFinished(files?: File[]): Promise<void>;
637
- /**
638
- * Writes the report to an output file if specified in the config,
639
- * or logs it to the console otherwise.
640
- * @param report
641
- */
642
- writeReport(report: string): Promise<void>;
643
- protected getFailureLocation(test: Test): Callsite | undefined;
644
- }
645
-
646
- declare class VerboseReporter extends DefaultReporter {
647
- constructor();
648
- onTaskUpdate(packs: TaskResultPack[]): void;
649
- }
650
-
651
- declare class TapReporter implements Reporter {
652
- protected ctx: Vitest;
653
- private logger;
654
- onInit(ctx: Vitest): void;
655
- static getComment(task: Task): string;
656
- private logErrorDetails;
657
- protected logTasks(tasks: Task[]): void;
658
- onFinished(files?: File[]): Promise<void>;
659
- }
660
-
661
- declare class JUnitReporter implements Reporter {
662
- private ctx;
663
- private reportFile?;
664
- private baseLog;
665
- private logger;
666
- onInit(ctx: Vitest): Promise<void>;
667
- writeElement(name: string, attrs: Record<string, any>, children: () => Promise<void>): Promise<void>;
668
- writeErrorDetails(error: ErrorWithDiff): Promise<void>;
669
- writeLogs(task: Task, type: 'err' | 'out'): Promise<void>;
670
- writeTasks(tasks: Task[], filename: string): Promise<void>;
671
- onFinished(files?: File[]): Promise<void>;
672
- }
673
-
674
- declare class TapFlatReporter extends TapReporter {
675
- onInit(ctx: Vitest): void;
676
- onFinished(files?: File[]): Promise<void>;
677
- }
678
-
679
- declare const ReportersMap: {
680
- default: typeof DefaultReporter;
681
- verbose: typeof VerboseReporter;
682
- dot: typeof DotReporter;
683
- json: typeof JsonReporter;
684
- tap: typeof TapReporter;
685
- 'tap-flat': typeof TapFlatReporter;
686
- junit: typeof JUnitReporter;
687
- };
688
- declare type BuiltinReporters = keyof typeof ReportersMap;
689
-
690
- declare type Awaitable<T> = T | PromiseLike<T>;
691
- declare type Nullable<T> = T | null | undefined;
692
- declare type Arrayable<T> = T | Array<T>;
693
- declare type ArgumentsType$1<T> = T extends (...args: infer U) => any ? U : never;
694
- declare type MergeInsertions<T> = T extends object ? {
695
- [K in keyof T]: MergeInsertions<T[K]>;
696
- } : T;
697
- declare type DeepMerge<F, S> = MergeInsertions<{
698
- [K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
699
- }>;
700
- declare type MutableArray<T extends readonly any[]> = {
701
- -readonly [k in keyof T]: T[k];
702
- };
703
- interface Constructable$1 {
704
- new (...args: any[]): any;
705
- }
706
- interface ModuleCache {
707
- promise?: Promise<any>;
708
- exports?: any;
709
- code?: string;
710
- }
711
- interface EnvironmentReturn {
712
- teardown: (global: any) => Awaitable<void>;
713
- }
714
- interface Environment {
715
- name: string;
716
- setup(global: any, options: Record<string, any>): Awaitable<EnvironmentReturn>;
717
- }
718
- interface UserConsoleLog {
719
- content: string;
720
- type: 'stdout' | 'stderr';
721
- taskId?: string;
722
- time: number;
723
- size: number;
724
- }
725
- interface Position {
726
- source?: string;
727
- line: number;
728
- column: number;
729
- }
730
- interface ParsedStack {
731
- method: string;
732
- file: string;
733
- line: number;
734
- column: number;
735
- sourcePos?: Position;
736
- }
737
- interface ErrorWithDiff extends Error {
738
- name: string;
739
- nameStr?: string;
740
- stack?: string;
741
- stackStr?: string;
742
- stacks?: ParsedStack[];
743
- showDiff?: boolean;
744
- actual?: any;
745
- expected?: any;
746
- operator?: string;
747
- type?: string;
748
- }
749
- interface ModuleGraphData {
750
- graph: Record<string, string[]>;
751
- externalized: string[];
752
- inlined: string[];
753
- }
754
-
755
- declare type CoverageReporter = 'clover' | 'cobertura' | 'html-spa' | 'html' | 'json-summary' | 'json' | 'lcov' | 'lcovonly' | 'none' | 'teamcity' | 'text-lcov' | 'text-summary' | 'text';
756
- interface C8Options {
757
- /**
758
- * Enable coverage, pass `--coverage` to enable
759
- *
760
- * @default false
761
- */
762
- enabled?: boolean;
763
- /**
764
- * Directory to write coverage report to
765
- */
766
- reportsDirectory?: string;
767
- /**
768
- * Clean coverage before running tests
769
- *
770
- * @default true
771
- */
772
- clean?: boolean;
773
- /**
774
- * Clean coverage report on watch rerun
775
- *
776
- * @default false
777
- */
778
- cleanOnRerun?: boolean;
779
- /**
780
- * Allow files from outside of your cwd.
781
- *
782
- * @default false
783
- */
784
- allowExternal?: any;
785
- /**
786
- * Reporters
787
- *
788
- * @default 'text'
789
- */
790
- reporter?: Arrayable<CoverageReporter>;
791
- /**
792
- * Exclude coverage under /node_modules/
793
- *
794
- * @default true
795
- */
796
- excludeNodeModules?: boolean;
797
- exclude?: string[];
798
- include?: string[];
799
- skipFull?: boolean;
800
- extension?: string | string[];
801
- all?: boolean;
802
- src?: string[];
803
- 100?: boolean;
804
- lines?: number;
805
- functions?: number;
806
- branches?: number;
807
- statements?: number;
808
- }
809
- interface ResolvedC8Options extends Required<C8Options> {
810
- tempDirectory: string;
811
- }
812
-
813
- interface JSDOMOptions {
814
- /**
815
- * The html content for the test.
816
- *
817
- * @default '<!DOCTYPE html>'
818
- */
819
- html?: string | Buffer | ArrayBufferLike;
820
- /**
821
- * referrer just affects the value read from document.referrer.
822
- * It defaults to no referrer (which reflects as the empty string).
823
- */
824
- referrer?: string;
825
- /**
826
- * userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources.
827
- *
828
- * @default `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`
829
- */
830
- userAgent?: string;
831
- /**
832
- * url sets the value returned by window.location, document.URL, and document.documentURI,
833
- * and affects things like resolution of relative URLs within the document
834
- * and the same-origin restrictions and referrer used while fetching subresources.
835
- *
836
- * @default 'http://localhost:3000'.
837
- */
838
- url?: string;
839
- /**
840
- * contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
841
- * Values that are not "text/html" or an XML mime type will throw.
842
- *
843
- * @default 'text/html'.
844
- */
845
- contentType?: string;
846
- /**
847
- * The maximum size in code units for the separate storage areas used by localStorage and sessionStorage.
848
- * Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set
849
- * to 5,000,000 code units per origin, as inspired by the HTML specification.
850
- *
851
- * @default 5_000_000
852
- */
853
- storageQuota?: number;
854
- /**
855
- * Enable console?
856
- *
857
- * @default false
858
- */
859
- console?: boolean;
860
- /**
861
- * jsdom does not have the capability to render visual content, and will act like a headless browser by default.
862
- * It provides hints to web pages through APIs such as document.hidden that their content is not visible.
863
- *
864
- * When the `pretendToBeVisual` option is set to `true`, jsdom will pretend that it is rendering and displaying
865
- * content.
866
- *
867
- * @default true
868
- */
869
- pretendToBeVisual?: boolean;
870
- /**
871
- * `includeNodeLocations` preserves the location info produced by the HTML parser,
872
- * allowing you to retrieve it with the nodeLocation() method (described below).
873
- *
874
- * It defaults to false to give the best performance,
875
- * and cannot be used with an XML content type since our XML parser does not support location info.
876
- *
877
- * @default false
878
- */
879
- includeNodeLocations?: boolean | undefined;
880
- /**
881
- * @default 'dangerously'
882
- */
883
- runScripts?: 'dangerously' | 'outside-only';
884
- /**
885
- * Enable CookieJar
886
- *
887
- * @default false
888
- */
889
- cookieJar?: boolean;
890
- resources?: 'usable' | any;
891
- }
892
-
893
- declare type ChainableFunction<T extends string, Args extends any[], R = any> = {
894
- (...args: Args): R;
895
- } & {
896
- [x in T]: ChainableFunction<T, Args, R>;
897
- };
898
-
899
- declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
900
- declare type TaskState = RunMode | 'pass' | 'fail';
901
- interface TaskBase {
902
- id: string;
903
- name: string;
904
- mode: RunMode;
905
- concurrent?: boolean;
906
- shuffle?: boolean;
907
- suite?: Suite;
908
- file?: File;
909
- result?: TaskResult;
910
- logs?: UserConsoleLog[];
911
- }
912
- interface TaskResult {
913
- state: TaskState;
914
- duration?: number;
915
- startTime?: number;
916
- heap?: number;
917
- error?: ErrorWithDiff;
918
- htmlError?: string;
919
- hooks?: Partial<Record<keyof SuiteHooks, TaskState>>;
920
- }
921
- declare type TaskResultPack = [id: string, result: TaskResult | undefined];
922
- interface Suite extends TaskBase {
923
- type: 'suite';
924
- tasks: Task[];
925
- filepath?: string;
926
- }
927
- interface File extends Suite {
928
- filepath: string;
929
- collectDuration?: number;
930
- setupDuration?: number;
931
- }
932
- interface Test<ExtraContext = {}> extends TaskBase {
933
- type: 'test';
934
- suite: Suite;
935
- result?: TaskResult;
936
- fails?: boolean;
937
- context: TestContext & ExtraContext;
938
- }
939
- declare type Task = Test | Suite | File;
940
- declare type DoneCallback = (error?: any) => void;
941
- declare type TestFunction<ExtraContext = {}> = (context: TestContext & ExtraContext) => Awaitable<any> | void;
942
- declare type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
943
- 1: [T[0]];
944
- 2: [T[0], T[1]];
945
- 3: [T[0], T[1], T[2]];
946
- 4: [T[0], T[1], T[2], T[3]];
947
- 5: [T[0], T[1], T[2], T[3], T[4]];
948
- 6: [T[0], T[1], T[2], T[3], T[4], T[5]];
949
- 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]];
950
- 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]];
951
- 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]];
952
- 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]];
953
- fallback: Array<T extends ReadonlyArray<infer U> ? U : any>;
954
- }[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'];
955
- interface EachFunction {
956
- <T extends any[] | [any]>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T) => Awaitable<void>) => void;
957
- <T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): (name: string, fn: (...args: ExtractEachCallbackArgs<T>) => Awaitable<void>) => void;
958
- <T>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T[]) => Awaitable<void>) => void;
959
- }
960
- declare type ChainableTestAPI<ExtraContext = {}> = ChainableFunction<'concurrent' | 'only' | 'skip' | 'todo' | 'fails', [
961
- name: string,
962
- fn?: TestFunction<ExtraContext>,
963
- timeout?: number
964
- ], void>;
965
- declare type TestAPI<ExtraContext = {}> = ChainableTestAPI<ExtraContext> & {
966
- each: EachFunction;
967
- skipIf(condition: any): ChainableTestAPI<ExtraContext>;
968
- runIf(condition: any): ChainableTestAPI<ExtraContext>;
969
- };
970
- declare type ChainableSuiteAPI<ExtraContext = {}> = ChainableFunction<'concurrent' | 'only' | 'skip' | 'todo' | 'shuffle', [
971
- name: string,
972
- factory?: SuiteFactory
973
- ], SuiteCollector<ExtraContext>>;
974
- declare type SuiteAPI<ExtraContext = {}> = ChainableSuiteAPI & {
975
- each: EachFunction;
976
- skipIf(condition: any): ChainableSuiteAPI<ExtraContext>;
977
- runIf(condition: any): ChainableSuiteAPI<ExtraContext>;
978
- };
979
- declare type HookListener<T extends any[], Return = void> = (...args: T) => Awaitable<Return>;
980
- declare type HookCleanupCallback = (() => Awaitable<unknown>) | void;
981
- interface SuiteHooks {
982
- beforeAll: HookListener<[Suite | File], HookCleanupCallback>[];
983
- afterAll: HookListener<[Suite | File]>[];
984
- beforeEach: HookListener<[TestContext, Suite], HookCleanupCallback>[];
985
- afterEach: HookListener<[TestContext, Suite]>[];
986
- }
987
- interface SuiteCollector<ExtraContext = {}> {
988
- readonly name: string;
989
- readonly mode: RunMode;
990
- type: 'collector';
991
- test: TestAPI<ExtraContext>;
992
- tasks: (Suite | Test | SuiteCollector<ExtraContext>)[];
993
- collect: (file?: File) => Promise<Suite>;
994
- clear: () => void;
995
- on: <T extends keyof SuiteHooks>(name: T, ...fn: SuiteHooks[T]) => void;
996
- }
997
- declare type SuiteFactory = (test: (name: string, fn: TestFunction) => void) => Awaitable<void>;
998
- interface RuntimeContext {
999
- tasks: (SuiteCollector | Test)[];
1000
- currentSuite: SuiteCollector | null;
1001
- }
1002
- interface TestContext {
1003
- /**
1004
- * @deprecated Use promise instead
1005
- */
1006
- (error?: any): void;
1007
- /**
1008
- * Metadata of the current test
1009
- */
1010
- meta: Readonly<Test>;
1011
- /**
1012
- * A expect instance bound to the test
1013
- */
1014
- expect: Vi.ExpectStatic;
1015
- }
1016
-
1017
- interface Reporter {
1018
- onInit?(ctx: Vitest): void;
1019
- onPathsCollected?: (paths?: string[]) => Awaitable<void>;
1020
- onCollected?: (files?: File[]) => Awaitable<void>;
1021
- onFinished?: (files?: File[], errors?: unknown[]) => Awaitable<void>;
1022
- onTaskUpdate?: (packs: TaskResultPack[]) => Awaitable<void>;
1023
- onTestRemoved?: (trigger?: string) => Awaitable<void>;
1024
- onWatcherStart?: () => Awaitable<void>;
1025
- onWatcherRerun?: (files: string[], trigger?: string) => Awaitable<void>;
1026
- onServerRestart?: () => Awaitable<void>;
1027
- onUserConsoleLog?: (log: UserConsoleLog) => Awaitable<void>;
1028
- }
1029
-
1030
- declare type SnapshotData = Record<string, string>;
1031
- declare type SnapshotUpdateState = 'all' | 'new' | 'none';
1032
- interface SnapshotStateOptions {
1033
- updateSnapshot: SnapshotUpdateState;
1034
- expand?: boolean;
1035
- snapshotFormat?: OptionsReceived;
1036
- resolveSnapshotPath?: (path: string, extension: string) => string;
1037
- }
1038
- interface SnapshotMatchOptions {
1039
- testName: string;
1040
- received: unknown;
1041
- key?: string;
1042
- inlineSnapshot?: string;
1043
- isInline: boolean;
1044
- error?: Error;
1045
- }
1046
- interface SnapshotResult {
1047
- filepath: string;
1048
- added: number;
1049
- fileDeleted: boolean;
1050
- matched: number;
1051
- unchecked: number;
1052
- uncheckedKeys: Array<string>;
1053
- unmatched: number;
1054
- updated: number;
1055
- }
1056
- interface UncheckedSnapshot {
1057
- filePath: string;
1058
- keys: Array<string>;
1059
- }
1060
- interface SnapshotSummary {
1061
- added: number;
1062
- didUpdate: boolean;
1063
- failure: boolean;
1064
- filesAdded: number;
1065
- filesRemoved: number;
1066
- filesRemovedList: Array<string>;
1067
- filesUnmatched: number;
1068
- filesUpdated: number;
1069
- matched: number;
1070
- total: number;
1071
- unchecked: number;
1072
- uncheckedKeysByFile: Array<UncheckedSnapshot>;
1073
- unmatched: number;
1074
- updated: number;
1075
- }
1076
-
1077
- declare type BuiltinEnvironment = 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime';
1078
- declare type ApiConfig = Pick<CommonServerOptions, 'port' | 'strictPort' | 'host'>;
1079
-
1080
- interface EnvironmentOptions {
1081
- /**
1082
- * jsdom options.
1083
- */
1084
- jsdom?: JSDOMOptions;
1085
- }
1086
- interface InlineConfig {
1087
- /**
1088
- * Include globs for test files
1089
- *
1090
- * @default ['**\/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
1091
- */
1092
- include?: string[];
1093
- /**
1094
- * Exclude globs for test files
1095
- * @default ['node_modules', 'dist', '.idea', '.git', '.cache']
1096
- */
1097
- exclude?: string[];
1098
- /**
1099
- * Include globs for in-source test files
1100
- *
1101
- * @default []
1102
- */
1103
- includeSource?: string[];
1104
- /**
1105
- * Handling for dependencies inlining or externalizing
1106
- */
1107
- deps?: {
1108
- /**
1109
- * Externalize means that Vite will bypass the package to native Node.
1110
- *
1111
- * Externalized dependencies will not be applied Vite's transformers and resolvers.
1112
- * And does not support HMR on reload.
1113
- *
1114
- * Typically, packages under `node_modules` are externalized.
1115
- */
1116
- external?: (string | RegExp)[];
1117
- /**
1118
- * Vite will process inlined modules.
1119
- *
1120
- * This could be helpful to handle packages that ship `.js` in ESM format (that Node can't handle).
1121
- *
1122
- * If `true`, every dependency will be inlined
1123
- */
1124
- inline?: (string | RegExp)[] | true;
1125
- /**
1126
- * Interpret CJS module's default as named exports
1127
- *
1128
- * @default true
1129
- */
1130
- interopDefault?: boolean;
1131
- /**
1132
- * When a dependency is a valid ESM package, try to guess the cjs version based on the path.
1133
- * This will significantly improve the performance in huge repo, but might potentially
1134
- * cause some misalignment if a package have different logic in ESM and CJS mode.
1135
- *
1136
- * @default false
1137
- */
1138
- fallbackCJS?: boolean;
1139
- /**
1140
- * Use experimental Node loader to resolve imports inside node_modules using Vite resolve algorithm.
1141
- * @default true
1142
- */
1143
- registerNodeLoader?: boolean;
1144
- };
1145
- /**
1146
- * Base directory to scan for the test files
1147
- *
1148
- * @default `config.root`
1149
- */
1150
- dir?: string;
1151
- /**
1152
- * Register apis globally
1153
- *
1154
- * @default false
1155
- */
1156
- globals?: boolean;
1157
- /**
1158
- * Running environment
1159
- *
1160
- * Supports 'node', 'jsdom', 'happy-dom', 'edge-runtime'
1161
- *
1162
- * @default 'node'
1163
- */
1164
- environment?: BuiltinEnvironment;
1165
- /**
1166
- * Environment options.
1167
- */
1168
- environmentOptions?: EnvironmentOptions;
1169
- /**
1170
- * Update snapshot
1171
- *
1172
- * @default false
1173
- */
1174
- update?: boolean;
1175
- /**
1176
- * Watch mode
1177
- *
1178
- * @default true
1179
- */
1180
- watch?: boolean;
1181
- /**
1182
- * Project root
1183
- *
1184
- * @default process.cwd()
1185
- */
1186
- root?: string;
1187
- /**
1188
- * Custom reporter for output. Can contain one or more built-in report names, reporter instances,
1189
- * and/or paths to custom reporters
1190
- */
1191
- reporters?: Arrayable<BuiltinReporters | Reporter | Omit<string, BuiltinReporters>>;
1192
- /**
1193
- * diff output length
1194
- */
1195
- outputTruncateLength?: number;
1196
- /**
1197
- * number of diff output lines
1198
- */
1199
- outputDiffLines?: number;
1200
- /**
1201
- * Write test results to a file when the --reporter=json` or `--reporter=junit` option is also specified.
1202
- * Also definable individually per reporter by using an object instead.
1203
- */
1204
- outputFile?: string | (Partial<Record<BuiltinReporters, string>> & Record<string, string>);
1205
- /**
1206
- * Enable multi-threading
1207
- *
1208
- * @default true
1209
- */
1210
- threads?: boolean;
1211
- /**
1212
- * Maximum number of threads
1213
- *
1214
- * @default available CPUs
1215
- */
1216
- maxThreads?: number;
1217
- /**
1218
- * Minimum number of threads
1219
- *
1220
- * @default available CPUs
1221
- */
1222
- minThreads?: number;
1223
- /**
1224
- * Default timeout of a test in milliseconds
1225
- *
1226
- * @default 5000
1227
- */
1228
- testTimeout?: number;
1229
- /**
1230
- * Default timeout of a hook in milliseconds
1231
- *
1232
- * @default 10000
1233
- */
1234
- hookTimeout?: number;
1235
- /**
1236
- * Default timeout to wait for close when Vitest shuts down, in milliseconds
1237
- *
1238
- * @default 1000
1239
- */
1240
- teardownTimeout?: number;
1241
- /**
1242
- * Silent mode
1243
- *
1244
- * @default false
1245
- */
1246
- silent?: boolean;
1247
- /**
1248
- * Path to setup files
1249
- */
1250
- setupFiles?: string | string[];
1251
- /**
1252
- * Path to global setup files
1253
- */
1254
- globalSetup?: string | string[];
1255
- /**
1256
- * Glob pattern of file paths to be ignore from triggering watch rerun
1257
- */
1258
- watchExclude?: string[];
1259
- /**
1260
- * Glob patter of file paths that will trigger the whole suite rerun
1261
- *
1262
- * Useful if you are testing calling CLI commands
1263
- *
1264
- * @default []
1265
- */
1266
- forceRerunTriggers?: string[];
1267
- /**
1268
- * Isolate environment for each test file
1269
- *
1270
- * @default true
1271
- */
1272
- isolate?: boolean;
1273
- /**
1274
- * Coverage options
1275
- */
1276
- coverage?: C8Options;
1277
- /**
1278
- * run test names with the specified pattern
1279
- */
1280
- testNamePattern?: string | RegExp;
1281
- /**
1282
- * Will call `.mockClear()` on all spies before each test
1283
- * @default false
1284
- */
1285
- clearMocks?: boolean;
1286
- /**
1287
- * Will call `.mockReset()` on all spies before each test
1288
- * @default false
1289
- */
1290
- mockReset?: boolean;
1291
- /**
1292
- * Will call `.mockRestore()` on all spies before each test
1293
- * @default false
1294
- */
1295
- restoreMocks?: boolean;
1296
- /**
1297
- * Serve API options.
1298
- *
1299
- * When set to true, the default port is 51204.
1300
- *
1301
- * @default false
1302
- */
1303
- api?: boolean | number | ApiConfig;
1304
- /**
1305
- * Enable Vitest UI
1306
- * @internal WIP
1307
- */
1308
- ui?: boolean;
1309
- /**
1310
- * Use in browser environment
1311
- * @experimental
1312
- */
1313
- browser?: boolean;
1314
- /**
1315
- * Open UI automatically.
1316
- *
1317
- * @default true
1318
- */
1319
- open?: boolean;
1320
- /**
1321
- * Base url for the UI
1322
- *
1323
- * @default '/__vitest__/'
1324
- */
1325
- uiBase?: string;
1326
- /**
1327
- * Determine the transform method of modules
1328
- */
1329
- transformMode?: {
1330
- /**
1331
- * Use SSR transform pipeline for the specified files.
1332
- * Vite plugins will receive `ssr: true` flag when processing those files.
1333
- *
1334
- * @default [/\.([cm]?[jt]sx?|json)$/]
1335
- */
1336
- ssr?: RegExp[];
1337
- /**
1338
- * First do a normal transform pipeline (targeting browser),
1339
- * then then do a SSR rewrite to run the code in Node.
1340
- * Vite plugins will receive `ssr: false` flag when processing those files.
1341
- *
1342
- * @default other than `ssr`
1343
- */
1344
- web?: RegExp[];
1345
- };
1346
- /**
1347
- * Format options for snapshot testing.
1348
- */
1349
- snapshotFormat?: PrettyFormatOptions;
1350
- /**
1351
- * Resolve custom snapshot path
1352
- */
1353
- resolveSnapshotPath?: (path: string, extension: string) => string;
1354
- /**
1355
- * Pass with no tests
1356
- */
1357
- passWithNoTests?: boolean;
1358
- /**
1359
- * Allow tests and suites that are marked as only
1360
- */
1361
- allowOnly?: boolean;
1362
- /**
1363
- * Show heap usage after each test. Usefull for debugging memory leaks.
1364
- */
1365
- logHeapUsage?: boolean;
1366
- /**
1367
- * Custom environment variables assigned to `process.env` before running tests.
1368
- */
1369
- env?: Record<string, string>;
1370
- /**
1371
- * Options for @sinon/fake-timers
1372
- */
1373
- fakeTimers?: FakeTimerInstallOpts;
1374
- /**
1375
- * Custom handler for console.log in tests.
1376
- *
1377
- * Return `false` to ignore the log.
1378
- */
1379
- onConsoleLog?: (log: string, type: 'stdout' | 'stderr') => false | void;
1380
- /**
1381
- * Indicates if CSS files should be processed.
1382
- *
1383
- * When excluded, the CSS files will be replaced with empty strings to bypass the subsequent processing.
1384
- *
1385
- * @default { include: [/\.module\./] }
1386
- */
1387
- css?: boolean | {
1388
- include?: RegExp | RegExp[];
1389
- exclude?: RegExp | RegExp[];
1390
- };
1391
- /**
1392
- * A number of tests that are allowed to run at the same time marked with `test.concurrent`.
1393
- * @default 5
1394
- */
1395
- maxConcurrency?: number;
1396
- /**
1397
- * Options for configuring cache policy.
1398
- * @default { dir: 'node_modules/.vitest' }
1399
- */
1400
- cache?: false | {
1401
- dir?: string;
1402
- };
1403
- /**
1404
- * Options for configuring the order of running tests.
1405
- */
1406
- sequence?: {
1407
- /**
1408
- * Class that handles sorting and sharding algorithm.
1409
- * If you only need to change sorting, you can extend
1410
- * your custom sequencer from `BaseSequencer` from `vitest/node`.
1411
- * @default BaseSequencer
1412
- */
1413
- sequencer?: TestSequencerConstructor;
1414
- /**
1415
- * Should tests run in random order.
1416
- * @default false
1417
- */
1418
- shuffle?: boolean;
1419
- /**
1420
- * Seed for the random number generator.
1421
- * @default Date.now()
1422
- */
1423
- seed?: number;
1424
- };
1425
- /**
1426
- * Specifies an `Object`, or an `Array` of `Object`,
1427
- * which defines aliases used to replace values in `import` or `require` statements.
1428
- * Will be merged with the default aliases inside `resolve.alias`.
1429
- */
1430
- alias?: AliasOptions;
1431
- /**
1432
- * Ignore any unhandled errors that occur
1433
- */
1434
- dangerouslyIgnoreUnhandledErrors?: boolean;
1435
- }
1436
- interface UserConfig extends InlineConfig {
1437
- /**
1438
- * Path to the config file.
1439
- *
1440
- * Default resolving to one of:
1441
- * - `vitest.config.js`
1442
- * - `vitest.config.ts`
1443
- * - `vite.config.js`
1444
- * - `vite.config.ts`
1445
- */
1446
- config?: string | undefined;
1447
- /**
1448
- * Use happy-dom
1449
- */
1450
- dom?: boolean;
1451
- /**
1452
- * Run tests that cover a list of source files
1453
- */
1454
- related?: string[] | string;
1455
- /**
1456
- * Overrides Vite mode
1457
- * @default 'test'
1458
- */
1459
- mode?: string;
1460
- /**
1461
- * Runs tests that are affected by the changes in the repository, or between specified branch or commit hash
1462
- * Requires initialized git repository
1463
- * @default false
1464
- */
1465
- changed?: boolean | string;
1466
- /**
1467
- * Test suite shard to execute in a format of <index>/<count>.
1468
- * Will divide tests into a `count` numbers, and run only the `indexed` part.
1469
- * Cannot be used with enabled watch.
1470
- * @example --shard=2/3
1471
- */
1472
- shard?: string;
1473
- }
1474
- interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'shard' | 'cache' | 'sequence'> {
1475
- base?: string;
1476
- config?: string;
1477
- filters?: string[];
1478
- testNamePattern?: RegExp;
1479
- related?: string[];
1480
- coverage: ResolvedC8Options;
1481
- snapshotOptions: SnapshotStateOptions;
1482
- reporters: (Reporter | BuiltinReporters)[];
1483
- defines: Record<string, any>;
1484
- api?: ApiConfig;
1485
- shard?: {
1486
- index: number;
1487
- count: number;
1488
- };
1489
- cache: {
1490
- dir: string;
1491
- } | false;
1492
- sequence: {
1493
- sequencer: TestSequencerConstructor;
1494
- shuffle?: boolean;
1495
- seed?: number;
1496
- };
1497
- }
1498
-
1499
- declare type VitestInlineConfig = InlineConfig;
1500
- declare module 'vite' {
1501
- interface UserConfig {
1502
- /**
1503
- * Options for Vitest
1504
- */
1505
- test?: VitestInlineConfig;
1506
- }
1507
- }
1508
-
1509
- declare type Formatter = (input: string | number | null | undefined) => string;
1510
-
1511
- interface MatcherHintOptions {
1512
- comment?: string;
1513
- expectedColor?: Formatter;
1514
- isDirectExpectCall?: boolean;
1515
- isNot?: boolean;
1516
- promise?: string;
1517
- receivedColor?: Formatter;
1518
- secondArgument?: string;
1519
- secondArgumentColor?: Formatter;
1520
- }
1521
- interface DiffOptions {
1522
- aAnnotation?: string;
1523
- aColor?: Formatter;
1524
- aIndicator?: string;
1525
- bAnnotation?: string;
1526
- bColor?: Formatter;
1527
- bIndicator?: string;
1528
- changeColor?: Formatter;
1529
- changeLineTrailingSpaceColor?: Formatter;
1530
- commonColor?: Formatter;
1531
- commonIndicator?: string;
1532
- commonLineTrailingSpaceColor?: Formatter;
1533
- contextLines?: number;
1534
- emptyFirstOrLastLinePlaceholder?: string;
1535
- expand?: boolean;
1536
- includeChangeCounts?: boolean;
1537
- omitAnnotationLines?: boolean;
1538
- patchColor?: Formatter;
1539
- compareKeys?: any;
1540
- }
1541
-
1542
- declare const EXPECTED_COLOR: Formatter;
1543
- declare const RECEIVED_COLOR: Formatter;
1544
- declare const INVERTED_COLOR: Formatter;
1545
- declare const BOLD_WEIGHT: Formatter;
1546
- declare const DIM_COLOR: Formatter;
1547
- declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string;
1548
- declare function stringify(object: unknown, maxDepth?: number, options?: PrettyFormatOptions): string;
1549
- declare const printReceived: (object: unknown) => string;
1550
- declare const printExpected: (value: unknown) => string;
1551
- declare function diff(a: any, b: any, options?: DiffOptions): string;
1552
-
1553
- declare const jestMatcherUtils_EXPECTED_COLOR: typeof EXPECTED_COLOR;
1554
- declare const jestMatcherUtils_RECEIVED_COLOR: typeof RECEIVED_COLOR;
1555
- declare const jestMatcherUtils_INVERTED_COLOR: typeof INVERTED_COLOR;
1556
- declare const jestMatcherUtils_BOLD_WEIGHT: typeof BOLD_WEIGHT;
1557
- declare const jestMatcherUtils_DIM_COLOR: typeof DIM_COLOR;
1558
- declare const jestMatcherUtils_matcherHint: typeof matcherHint;
1559
- declare const jestMatcherUtils_stringify: typeof stringify;
1560
- declare const jestMatcherUtils_printReceived: typeof printReceived;
1561
- declare const jestMatcherUtils_printExpected: typeof printExpected;
1562
- declare const jestMatcherUtils_diff: typeof diff;
1563
- declare namespace jestMatcherUtils {
1564
- export {
1565
- jestMatcherUtils_EXPECTED_COLOR as EXPECTED_COLOR,
1566
- jestMatcherUtils_RECEIVED_COLOR as RECEIVED_COLOR,
1567
- jestMatcherUtils_INVERTED_COLOR as INVERTED_COLOR,
1568
- jestMatcherUtils_BOLD_WEIGHT as BOLD_WEIGHT,
1569
- jestMatcherUtils_DIM_COLOR as DIM_COLOR,
1570
- jestMatcherUtils_matcherHint as matcherHint,
1571
- jestMatcherUtils_stringify as stringify,
1572
- jestMatcherUtils_printReceived as printReceived,
1573
- jestMatcherUtils_printExpected as printExpected,
1574
- jestMatcherUtils_diff as diff,
1575
- };
1576
- }
1577
-
1578
- /**
1579
- * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
1580
- *
1581
- * This source code is licensed under the MIT license found in the
1582
- * LICENSE file in the root directory of this source tree.
1583
- */
1584
-
1585
- interface SnapshotReturnOptions {
1586
- actual: string;
1587
- count: number;
1588
- expected?: string;
1589
- key: string;
1590
- pass: boolean;
1591
- }
1592
- interface SaveStatus {
1593
- deleted: boolean;
1594
- saved: boolean;
1595
- }
1596
- declare class SnapshotState {
1597
- testFilePath: string;
1598
- snapshotPath: string;
1599
- private _counters;
1600
- private _dirty;
1601
- private _updateSnapshot;
1602
- private _snapshotData;
1603
- private _initialData;
1604
- private _inlineSnapshots;
1605
- private _uncheckedKeys;
1606
- private _snapshotFormat;
1607
- added: number;
1608
- expand: boolean;
1609
- matched: number;
1610
- unmatched: number;
1611
- updated: number;
1612
- constructor(testFilePath: string, snapshotPath: string, options: SnapshotStateOptions);
1613
- markSnapshotsAsCheckedForTest(testName: string): void;
1614
- private _inferInlineSnapshotStack;
1615
- private _addSnapshot;
1616
- clear(): void;
1617
- save(): Promise<SaveStatus>;
1618
- getUncheckedCount(): number;
1619
- getUncheckedKeys(): Array<string>;
1620
- removeUncheckedKeys(): void;
1621
- match({ testName, received, key, inlineSnapshot, isInline, error, }: SnapshotMatchOptions): SnapshotReturnOptions;
1622
- pack(): Promise<SnapshotResult>;
1623
- }
1624
-
1625
- declare type Tester = (a: any, b: any) => boolean | undefined;
1626
- interface MatcherState {
1627
- assertionCalls: number;
1628
- currentTestName?: string;
1629
- dontThrow?: () => void;
1630
- error?: Error;
1631
- equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
1632
- expand?: boolean;
1633
- expectedAssertionsNumber?: number | null;
1634
- expectedAssertionsNumberErrorGen?: (() => Error) | null;
1635
- isExpectingAssertions?: boolean;
1636
- isExpectingAssertionsError?: Error | null;
1637
- isNot: boolean;
1638
- promise: string;
1639
- snapshotState: SnapshotState;
1640
- suppressedErrors: Array<Error>;
1641
- testPath?: string;
1642
- utils: typeof jestMatcherUtils & {
1643
- iterableEquality: Tester;
1644
- subsetEquality: Tester;
1645
- };
1646
- }
1647
- interface SyncExpectationResult {
1648
- pass: boolean;
1649
- message: () => string;
1650
- actual?: any;
1651
- expected?: any;
1652
- }
1653
- declare type AsyncExpectationResult = Promise<SyncExpectationResult>;
1654
- declare type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
1655
- interface RawMatcherFn<T extends MatcherState = MatcherState> {
1656
- (this: T, received: any, expected: any, options?: any): ExpectationResult;
1657
- }
1658
- declare type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>>;
1659
-
1660
- declare type Promisify<O> = {
1661
- [K in keyof O]: O[K] extends (...args: infer A) => infer R ? O extends R ? Promisify<O[K]> : (...args: A) => Promise<R> : O[K];
1662
- };
1663
- declare global {
1664
- namespace jest {
1665
- interface Matchers<R, T = {}> {
1666
- }
1667
- }
1668
- namespace Vi {
1669
- interface ExpectStatic extends Chai.ExpectStatic, AsymmetricMatchersContaining {
1670
- <T>(actual: T, message?: string): Vi.Assertion<T>;
1671
- extend(expects: MatchersObject): void;
1672
- assertions(expected: number): void;
1673
- hasAssertions(): void;
1674
- anything(): any;
1675
- any(constructor: unknown): any;
1676
- addSnapshotSerializer(plugin: Plugin): void;
1677
- getState(): MatcherState;
1678
- setState(state: Partial<MatcherState>): void;
1679
- not: AsymmetricMatchersContaining;
1680
- }
1681
- interface AsymmetricMatchersContaining {
1682
- stringContaining(expected: string): any;
1683
- objectContaining(expected: any): any;
1684
- arrayContaining<T = unknown>(expected: Array<T>): any;
1685
- stringMatching(expected: string | RegExp): any;
1686
- }
1687
- interface JestAssertion<T = any> extends jest.Matchers<void, T> {
1688
- toMatchSnapshot<U extends {
1689
- [P in keyof T]: any;
1690
- }>(snapshot: Partial<U>, message?: string): void;
1691
- toMatchSnapshot(message?: string): void;
1692
- matchSnapshot<U extends {
1693
- [P in keyof T]: any;
1694
- }>(snapshot: Partial<U>, message?: string): void;
1695
- matchSnapshot(message?: string): void;
1696
- toMatchInlineSnapshot<U extends {
1697
- [P in keyof T]: any;
1698
- }>(properties: Partial<U>, snapshot?: string, message?: string): void;
1699
- toMatchInlineSnapshot(snapshot?: string, message?: string): void;
1700
- toThrowErrorMatchingSnapshot(message?: string): void;
1701
- toThrowErrorMatchingInlineSnapshot(snapshot?: string, message?: string): void;
1702
- toEqual<E>(expected: E): void;
1703
- toStrictEqual<E>(expected: E): void;
1704
- toBe<E>(expected: E): void;
1705
- toMatch(expected: string | RegExp): void;
1706
- toMatchObject<E extends {} | any[]>(expected: E): void;
1707
- toContain<E>(item: E): void;
1708
- toContainEqual<E>(item: E): void;
1709
- toBeTruthy(): void;
1710
- toBeFalsy(): void;
1711
- toBeGreaterThan(num: number | bigint): void;
1712
- toBeGreaterThanOrEqual(num: number | bigint): void;
1713
- toBeLessThan(num: number | bigint): void;
1714
- toBeLessThanOrEqual(num: number | bigint): void;
1715
- toBeNaN(): void;
1716
- toBeUndefined(): void;
1717
- toBeNull(): void;
1718
- toBeDefined(): void;
1719
- toBeTypeOf(expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined'): void;
1720
- toBeInstanceOf<E>(expected: E): void;
1721
- toBeCalledTimes(times: number): void;
1722
- toHaveLength(length: number): void;
1723
- toHaveProperty<E>(property: string | string[], value?: E): void;
1724
- toBeCloseTo(number: number, numDigits?: number): void;
1725
- toHaveBeenCalledTimes(times: number): void;
1726
- toHaveBeenCalledOnce(): void;
1727
- toHaveBeenCalled(): void;
1728
- toBeCalled(): void;
1729
- toHaveBeenCalledWith<E extends any[]>(...args: E): void;
1730
- toBeCalledWith<E extends any[]>(...args: E): void;
1731
- toHaveBeenNthCalledWith<E extends any[]>(n: number, ...args: E): void;
1732
- nthCalledWith<E extends any[]>(nthCall: number, ...args: E): void;
1733
- toHaveBeenLastCalledWith<E extends any[]>(...args: E): void;
1734
- lastCalledWith<E extends any[]>(...args: E): void;
1735
- toThrow(expected?: string | Constructable$1 | RegExp | Error): void;
1736
- toThrowError(expected?: string | Constructable$1 | RegExp | Error): void;
1737
- toReturn(): void;
1738
- toHaveReturned(): void;
1739
- toReturnTimes(times: number): void;
1740
- toHaveReturnedTimes(times: number): void;
1741
- toReturnWith<E>(value: E): void;
1742
- toHaveReturnedWith<E>(value: E): void;
1743
- toHaveLastReturnedWith<E>(value: E): void;
1744
- lastReturnedWith<E>(value: E): void;
1745
- toHaveNthReturnedWith<E>(nthCall: number, value: E): void;
1746
- nthReturnedWith<E>(nthCall: number, value: E): void;
1747
- toSatisfy<E>(matcher: (value: E) => boolean, message?: string): void;
1748
- }
1749
- type VitestAssertion<A, T> = {
1750
- [K in keyof A]: A[K] extends Chai.Assertion ? Assertion<T> : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion<A[K], T>;
1751
- } & ((type: string, message?: string) => Assertion);
1752
- interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T> {
1753
- resolves: Promisify<Assertion<T>>;
1754
- rejects: Promisify<Assertion<T>>;
1755
- }
1756
- }
1757
- }
1758
-
1759
- declare type ArgumentsType<T> = T extends (...args: infer A) => any ? A : never;
1760
- declare type ReturnType$1<T> = T extends (...args: any) => infer R ? R : never;
1761
- declare type PromisifyFn<T> = ReturnType$1<T> extends Promise<any> ? T : (...args: ArgumentsType<T>) => Promise<Awaited<ReturnType$1<T>>>;
1762
- declare type BirpcFn<T> = PromisifyFn<T> & {
1763
- /**
1764
- * Send event without asking for response
1765
- */
1766
- asEvent(...args: ArgumentsType<T>): void;
1767
- };
1768
- declare type BirpcReturn<RemoteFunctions> = {
1769
- [K in keyof RemoteFunctions]: BirpcFn<RemoteFunctions[K]>;
1770
- };
1771
-
1772
- interface WorkerContext {
1773
- workerId: number;
1774
- port: MessagePort;
1775
- config: ResolvedConfig;
1776
- files: string[];
1777
- invalidates?: string[];
1778
- }
1779
- declare type ResolveIdFunction = (id: string, importer?: string) => Promise<ViteNodeResolveId | null>;
1780
- interface WorkerRPC {
1781
- fetch: FetchFunction;
1782
- resolveId: ResolveIdFunction;
1783
- getSourceMap: (id: string, force?: boolean) => Promise<RawSourceMap | undefined>;
1784
- onFinished: (files: File[], errors?: unknown[]) => void;
1785
- onWorkerExit: (code?: number) => void;
1786
- onPathsCollected: (paths: string[]) => void;
1787
- onUserConsoleLog: (log: UserConsoleLog) => void;
1788
- onUnhandledRejection: (err: unknown) => void;
1789
- onCollected: (files: File[]) => void;
1790
- onTaskUpdate: (pack: TaskResultPack[]) => void;
1791
- snapshotSaved: (snapshot: SnapshotResult) => void;
1792
- resolveSnapshotPath: (testPath: string) => string;
1793
- }
1794
- interface WorkerGlobalState {
1795
- ctx: WorkerContext;
1796
- config: ResolvedConfig;
1797
- rpc: BirpcReturn<WorkerRPC>;
1798
- current?: Test;
1799
- filepath?: string;
1800
- moduleCache: ModuleCacheMap;
1801
- browserHashMap?: Map<string, string>;
1802
- mockMap: MockMap;
1803
- }
1804
-
1805
- interface MockResultReturn<T> {
1806
- type: 'return';
1807
- value: T;
1808
- }
1809
- interface MockResultIncomplete {
1810
- type: 'incomplete';
1811
- value: undefined;
1812
- }
1813
- interface MockResultThrow {
1814
- type: 'throw';
1815
- value: any;
1816
- }
1817
- declare type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
1818
- interface MockContext<TArgs, TReturns> {
1819
- calls: TArgs[];
1820
- instances: TReturns[];
1821
- invocationCallOrder: number[];
1822
- results: MockResult<TReturns>[];
1823
- lastCall: TArgs | undefined;
1824
- }
1825
- declare type Procedure = (...args: any[]) => any;
1826
- declare type Methods<T> = {
1827
- [K in keyof T]: T[K] extends Procedure ? K : never;
1828
- }[keyof T] & (string | symbol);
1829
- declare type Properties<T> = {
1830
- [K in keyof T]: T[K] extends Procedure ? never : K;
1831
- }[keyof T] & (string | symbol);
1832
- declare type Classes<T> = {
1833
- [K in keyof T]: T[K] extends new (...args: any[]) => any ? K : never;
1834
- }[keyof T] & (string | symbol);
1835
- interface SpyInstance<TArgs extends any[] = any[], TReturns = any> {
1836
- getMockName(): string;
1837
- mockName(n: string): this;
1838
- mock: MockContext<TArgs, TReturns>;
1839
- mockClear(): this;
1840
- mockReset(): this;
1841
- mockRestore(): void;
1842
- getMockImplementation(): ((...args: TArgs) => TReturns) | undefined;
1843
- mockImplementation(fn: ((...args: TArgs) => TReturns) | (() => Promise<TReturns>)): this;
1844
- mockImplementationOnce(fn: ((...args: TArgs) => TReturns) | (() => Promise<TReturns>)): this;
1845
- mockReturnThis(): this;
1846
- mockReturnValue(obj: TReturns): this;
1847
- mockReturnValueOnce(obj: TReturns): this;
1848
- mockResolvedValue(obj: Awaited<TReturns>): this;
1849
- mockResolvedValueOnce(obj: Awaited<TReturns>): this;
1850
- mockRejectedValue(obj: any): this;
1851
- mockRejectedValueOnce(obj: any): this;
1852
- }
1853
- interface MockInstance<A extends any[] = any[], R = any> extends SpyInstance<A, R> {
1854
- }
1855
- interface Mock<TArgs extends any[] = any, TReturns = any> extends SpyInstance<TArgs, TReturns> {
1856
- new (...args: TArgs): TReturns;
1857
- (...args: TArgs): TReturns;
1858
- }
1859
- declare type MaybeMockedConstructor<T> = T extends new (...args: Array<any>) => infer R ? Mock<ConstructorParameters<T>, R> : T;
1860
- declare type MockedFunction<T extends Procedure> = Mock<Parameters<T>, ReturnType<T>> & {
1861
- [K in keyof T]: T[K];
1862
- };
1863
- declare type MockedFunctionDeep<T extends Procedure> = Mock<Parameters<T>, ReturnType<T>> & MockedObjectDeep<T>;
1864
- declare type MockedObject<T> = MaybeMockedConstructor<T> & {
1865
- [K in Methods<T>]: T[K] extends Procedure ? MockedFunction<T[K]> : T[K];
1866
- } & {
1867
- [K in Properties<T>]: T[K];
1868
- };
1869
- declare type MockedObjectDeep<T> = MaybeMockedConstructor<T> & {
1870
- [K in Methods<T>]: T[K] extends Procedure ? MockedFunctionDeep<T[K]> : T[K];
1871
- } & {
1872
- [K in Properties<T>]: MaybeMockedDeep<T[K]>;
1873
- };
1874
- declare type MaybeMockedDeep<T> = T extends Procedure ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
1875
- declare type MaybeMocked<T> = T extends Procedure ? MockedFunction<T> : T extends object ? MockedObject<T> : T;
1876
- interface Constructable {
1877
- new (...args: any[]): any;
1878
- }
1879
- declare type MockedClass<T extends Constructable> = MockInstance<T extends new (...args: infer P) => any ? P : never, InstanceType<T>> & {
1880
- prototype: T extends {
1881
- prototype: any;
1882
- } ? Mocked<T['prototype']> : never;
1883
- } & T;
1884
- declare type Mocked<T> = {
1885
- [P in keyof T]: T[P] extends (...args: infer Args) => infer Returns ? MockInstance<Args, Returns> : T[P] extends Constructable ? MockedClass<T[P]> : T[P];
1886
- } & T;
1887
- declare type EnhancedSpy<TArgs extends any[] = any[], TReturns = any> = SpyInstance<TArgs, TReturns> & SpyImpl<TArgs, TReturns>;
1888
- declare function spyOn<T, S extends Properties<Required<T>>>(obj: T, methodName: S, accessType: 'get'): SpyInstance<[], T[S]>;
1889
- declare function spyOn<T, G extends Properties<Required<T>>>(obj: T, methodName: G, accessType: 'set'): SpyInstance<[T[G]], void>;
1890
- declare function spyOn<T, M extends (Methods<Required<T>> | Classes<Required<T>>)>(obj: T, methodName: M): Required<T>[M] extends (...args: infer A) => infer R | (new (...args: infer A) => infer R) ? SpyInstance<A, R> : never;
1891
- declare function fn<TArgs extends any[] = any[], R = any>(): Mock<TArgs, R>;
1892
- declare function fn<TArgs extends any[] = any[], R = any>(implementation: (...args: TArgs) => R): Mock<TArgs, R>;
1893
-
1894
- declare const suite: SuiteAPI<{}>;
1895
- declare const test: TestAPI<{}>;
1896
- declare const describe: SuiteAPI<{}>;
1897
- declare const it: TestAPI<{}>;
1898
-
1899
- declare const beforeAll: (fn: SuiteHooks['beforeAll'][0], timeout?: number) => void;
1900
- declare const afterAll: (fn: SuiteHooks['afterAll'][0], timeout?: number) => void;
1901
- declare const beforeEach: (fn: SuiteHooks['beforeEach'][0], timeout?: number) => void;
1902
- declare const afterEach: (fn: SuiteHooks['afterEach'][0], timeout?: number) => void;
9
+ import 'worker_threads';
10
+ import './mocker-5e2a8e41.js';
11
+ import 'tinyspy';
12
+ import 'fs';
1903
13
 
1904
14
  /**
1905
15
  * A simple wrapper for converting callback style to promise
@@ -1925,9 +35,6 @@ declare function runOnce<T>(fn: (() => T), key?: string): T;
1925
35
  */
1926
36
  declare function isFirstRun(): boolean;
1927
37
 
1928
- declare function createExpect(test?: Test): Vi.ExpectStatic;
1929
- declare const globalExpect: Vi.ExpectStatic;
1930
-
1931
38
  declare class VitestUtils {
1932
39
  private _timers;
1933
40
  private _mockedDate;
@@ -1990,6 +97,8 @@ declare class VitestUtils {
1990
97
  importMock<T>(path: string): Promise<MaybeMockedDeep<T>>;
1991
98
  /**
1992
99
  * Type helpers for TypeScript. In reality just returns the object that was passed.
100
+ *
101
+ * When `partial` is `true` it will expect a `Partial<T>` as a return value.
1993
102
  * @example
1994
103
  * import example from './example'
1995
104
  * vi.mock('./example')
@@ -2003,9 +112,26 @@ declare class VitestUtils {
2003
112
  * })
2004
113
  * @param item Anything that can be mocked
2005
114
  * @param deep If the object is deeply mocked
115
+ * @param options If the object is partially or deeply mocked
2006
116
  */
2007
117
  mocked<T>(item: T, deep?: false): MaybeMocked<T>;
2008
118
  mocked<T>(item: T, deep: true): MaybeMockedDeep<T>;
119
+ mocked<T>(item: T, options: {
120
+ partial?: false;
121
+ deep?: false;
122
+ }): MaybeMocked<T>;
123
+ mocked<T>(item: T, options: {
124
+ partial?: false;
125
+ deep: true;
126
+ }): MaybeMockedDeep<T>;
127
+ mocked<T>(item: T, options: {
128
+ partial: true;
129
+ deep?: false;
130
+ }): MaybePartiallyMocked<T>;
131
+ mocked<T>(item: T, options: {
132
+ partial: true;
133
+ deep: true;
134
+ }): MaybePartiallyMockedDeep<T>;
2009
135
  isMockFunction(fn: any): fn is EnhancedSpy;
2010
136
  clearAllMocks(): this;
2011
137
  resetAllMocks(): this;
@@ -2051,4 +177,4 @@ interface WebSocketHandlers {
2051
177
  interface WebSocketEvents extends Pick<Reporter, 'onCollected' | 'onFinished' | 'onTaskUpdate' | 'onUserConsoleLog' | 'onPathsCollected'> {
2052
178
  }
2053
179
 
2054
- export { ApiConfig, ArgumentsType$1 as ArgumentsType, Arrayable, Awaitable, BuiltinEnvironment, C8Options, Constructable$1 as Constructable, CoverageReporter, DeepMerge, DoneCallback, EnhancedSpy, Environment, EnvironmentOptions, EnvironmentReturn, ErrorWithDiff, File, HookCleanupCallback, HookListener, InlineConfig, JSDOMOptions, MergeInsertions, Mock, MockContext, MockInstance, Mocked, MockedClass, MockedFunction, MockedObject, ModuleCache, ModuleGraphData, MutableArray, Nullable, ParsedStack, Position, Reporter, ResolveIdFunction, ResolvedC8Options, ResolvedConfig, RunMode, RuntimeContext, SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, SpyInstance, Suite, SuiteAPI, SuiteCollector, SuiteFactory, SuiteHooks, Task, TaskBase, TaskResult, TaskResultPack, TaskState, Test, TestAPI, TestContext, TestFunction, TransformResultWithSource, UncheckedSnapshot, UserConfig, UserConsoleLog, Vitest, WebSocketEvents, WebSocketHandlers, WorkerContext, WorkerGlobalState, WorkerRPC, afterAll, afterEach, beforeAll, beforeEach, createExpect, describe, globalExpect as expect, getRunningMode, isFirstRun, isWatchMode, it, runOnce, suite, test, vi, vitest, withCallback };
180
+ export { TransformResultWithSource, WebSocketEvents, WebSocketHandlers, getRunningMode, isFirstRun, isWatchMode, runOnce, vi, vitest, withCallback };