vitest 1.0.0-beta.3 → 1.0.0-beta.4

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 (44) hide show
  1. package/LICENSE.md +17 -0
  2. package/dist/browser.d.ts +1 -2
  3. package/dist/browser.js +3 -3
  4. package/dist/child.js +5 -4
  5. package/dist/{chunk-api-setup.37a43981.js → chunk-api-setup.6d19ab38.js} +6 -2
  6. package/dist/{chunk-install-pkg.6349b322.js → chunk-install-pkg.e1d6323e.js} +4 -4
  7. package/dist/{chunk-integrations-globals.9df12d91.js → chunk-integrations-globals.2b099e04.js} +6 -6
  8. package/dist/cli.js +8 -5
  9. package/dist/config.cjs +1 -0
  10. package/dist/config.d.ts +1 -2
  11. package/dist/config.js +1 -0
  12. package/dist/coverage.d.ts +1 -2
  13. package/dist/entry-vm.js +8 -8
  14. package/dist/entry.js +8 -8
  15. package/dist/environments.d.ts +1 -2
  16. package/dist/execute.d.ts +2 -3
  17. package/dist/execute.js +1 -2
  18. package/dist/index.d.ts +233 -60
  19. package/dist/index.js +7 -7
  20. package/dist/node.d.ts +8 -4
  21. package/dist/node.js +4 -4
  22. package/dist/{reporters-1678fe04.d.ts → reporters-50c2bd49.d.ts} +39 -6
  23. package/dist/reporters.d.ts +1 -2
  24. package/dist/reporters.js +3 -3
  25. package/dist/runners.d.ts +1 -2
  26. package/dist/runners.js +5 -6
  27. package/dist/{suite-0579b50d.d.ts → suite-ad69b7cd.d.ts} +1 -1
  28. package/dist/suite.d.ts +2 -3
  29. package/dist/suite.js +3 -3
  30. package/dist/{vendor-benchmark.44931cfa.js → vendor-benchmark.b6befc50.js} +1 -1
  31. package/dist/{vendor-execute.e6e4e89b.js → vendor-execute.157302d6.js} +2 -3
  32. package/dist/vendor-global.c3664e75.js +14 -0
  33. package/dist/{vendor-index.29282562.js → vendor-index.2b92937b.js} +1 -1
  34. package/dist/{vendor-index.3d079eea.js → vendor-index.57925a34.js} +2 -2
  35. package/dist/{vendor-index.68ecee35.js → vendor-index.72df742e.js} +11 -4
  36. package/dist/{vendor-node.327f8f1f.js → vendor-node.65461b16.js} +762 -98
  37. package/dist/{vendor-reporters.b9600369.js → vendor-reporters.d24d80a4.js} +2 -2
  38. package/dist/{vendor-rpc.cbd8e972.js → vendor-rpc.171f65fb.js} +1 -1
  39. package/dist/{vendor-run-once.3e5ef7d7.js → vendor-run-once.fb836747.js} +1 -1
  40. package/dist/{vendor-vi.d30b47ae.js → vendor-vi.3baa7c4a.js} +32 -35
  41. package/dist/vm.js +6 -5
  42. package/dist/worker.js +6 -5
  43. package/package.json +8 -8
  44. package/dist/vendor-global.97e4527c.js +0 -9
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { TaskPopulated, File, TaskResultPack, CancelReason } from '@vitest/runner';
2
2
  export { Custom, DoneCallback, ExtendedContext, File, HookCleanupCallback, HookListener, OnTestFailedHandler, RunMode, RuntimeContext, SequenceHooks, SequenceSetupFiles, Suite, SuiteAPI, SuiteCollector, SuiteFactory, SuiteHooks, Task, TaskBase, TaskContext, TaskCustomOptions, TaskMeta, TaskResult, TaskResultPack, TaskState, Test, TestAPI, TestContext, TestFunction, TestOptions, afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, suite, test } from '@vitest/runner';
3
- export { b as bench } from './suite-0579b50d.js';
3
+ export { b as bench } from './suite-ad69b7cd.js';
4
4
  import { ExpectStatic } from '@vitest/expect';
5
5
  export { Assertion, AsymmetricMatchersContaining, ExpectStatic, JestAssertion } from '@vitest/expect';
6
- import { F as FakeTimerInstallOpts, M as MockFactoryWithHelper, k as RuntimeConfig, A as AfterSuiteRunMeta, l as UserConsoleLog, R as ResolvedConfig, m as ModuleGraphData, n as Reporter } from './reporters-1678fe04.js';
7
- export { D as ApiConfig, a4 as ArgumentsType, a3 as Arrayable, a1 as Awaitable, B as BaseCoverageOptions, ai as BenchFunction, ag as Benchmark, aj as BenchmarkAPI, ah as BenchmarkResult, af as BenchmarkUserOptions, x as BuiltinEnvironment, z as CSSModuleScopeStrategy, q as CollectLineNumbers, r as CollectLines, a6 as Constructable, u as Context, Y as ContextRPC, S as ContextTestEnvironment, ad as CoverageIstanbulOptions, b as CoverageOptions, c as CoverageProvider, d as CoverageProviderModule, ac as CoverageReporter, C as CoverageV8Options, ae as CustomProviderOptions, I as DepsOptimizationOptions, E as Environment, G as EnvironmentOptions, a8 as EnvironmentReturn, H as HappyDOMOptions, L as InlineConfig, J as JSDOMOptions, a7 as ModuleCache, a5 as MutableArray, a2 as Nullable, aa as OnServerRestartHandler, v as Pool, w as PoolOptions, P as ProjectConfig, o as RawErrsMap, ab as ReportContext, _ as ResolveIdFunction, a as ResolvedCoverageOptions, X as ResolvedTestEnvironment, t as RootAndTarget, Q as RunnerRPC, O as RuntimeRPC, K as TransformModePatterns, p as TscErrorInfo, N as TypecheckConfig, U as UserConfig, e as Vitest, y as VitestEnvironment, V as VitestRunMode, a9 as VmEnvironmentReturn, Z as WorkerContext, a0 as WorkerGlobalState, $ as WorkerRPC } from './reporters-1678fe04.js';
8
- import { spyOn, fn, MaybeMockedDeep, MaybeMocked, MaybePartiallyMocked, MaybePartiallyMockedDeep, EnhancedSpy } from '@vitest/spy';
9
- export { EnhancedSpy, Mock, MockContext, MockInstance, Mocked, MockedClass, MockedFunction, MockedObject, SpyInstance } from '@vitest/spy';
6
+ import { F as FakeTimerInstallOpts, M as MockFactoryWithHelper, l as RuntimeConfig, f as ProvidedContext, A as AfterSuiteRunMeta, m as UserConsoleLog, R as ResolvedConfig, n as ModuleGraphData, o as Reporter } from './reporters-50c2bd49.js';
7
+ export { G as ApiConfig, a5 as ArgumentsType, a4 as Arrayable, a2 as Awaitable, B as BaseCoverageOptions, aj as BenchFunction, ah as Benchmark, ak as BenchmarkAPI, ai as BenchmarkResult, ag as BenchmarkUserOptions, y as BuiltinEnvironment, D as CSSModuleScopeStrategy, r as CollectLineNumbers, t as CollectLines, a7 as Constructable, v as Context, Z as ContextRPC, X as ContextTestEnvironment, ae as CoverageIstanbulOptions, b as CoverageOptions, c as CoverageProvider, d as CoverageProviderModule, ad as CoverageReporter, C as CoverageV8Options, af as CustomProviderOptions, K as DepsOptimizationOptions, E as Environment, I as EnvironmentOptions, a9 as EnvironmentReturn, H as HappyDOMOptions, N as InlineConfig, J as JSDOMOptions, a8 as ModuleCache, a6 as MutableArray, a3 as Nullable, ab as OnServerRestartHandler, w as Pool, x as PoolOptions, P as ProjectConfig, p as RawErrsMap, ac as ReportContext, $ as ResolveIdFunction, a as ResolvedCoverageOptions, Y as ResolvedTestEnvironment, u as RootAndTarget, S as RunnerRPC, Q as RuntimeRPC, L as TransformModePatterns, q as TscErrorInfo, O as TypecheckConfig, U as UserConfig, e as Vitest, z as VitestEnvironment, V as VitestRunMode, aa as VmEnvironmentReturn, _ as WorkerContext, a1 as WorkerGlobalState, a0 as WorkerRPC } from './reporters-50c2bd49.js';
8
+ import { spyOn, fn, MaybeMockedDeep, MaybeMocked, MaybePartiallyMocked, MaybePartiallyMockedDeep, MockInstance } from '@vitest/spy';
9
+ export { Mock, MockContext, MockInstance, Mocked, MockedClass, MockedFunction, MockedObject, SpyInstance } from '@vitest/spy';
10
10
  export { SnapshotEnvironment } from '@vitest/snapshot/environment';
11
11
  import { SnapshotResult } from '@vitest/snapshot';
12
12
  export { SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, UncheckedSnapshot } from '@vitest/snapshot';
@@ -24,7 +24,6 @@ import 'vite-node/client';
24
24
  import '@vitest/snapshot/manager';
25
25
  import 'vite-node/server';
26
26
  import 'node:worker_threads';
27
- import 'rollup';
28
27
  import 'node:fs';
29
28
 
30
29
  declare type Not<T extends boolean> = T extends true ? false : true;
@@ -226,87 +225,232 @@ interface WaitUntilOptions extends Pick<WaitForOptions, 'interval' | 'timeout'>
226
225
  }
227
226
  declare function waitUntil<T>(callback: WaitUntilCallback<T>, options?: number | WaitUntilOptions): Promise<T>;
228
227
 
228
+ type ESModuleExports = Record<string, unknown>;
229
229
  interface VitestUtils {
230
+ /**
231
+ * Checks if fake timers are enabled.
232
+ */
230
233
  isFakeTimers(): boolean;
231
- useFakeTimers(config?: FakeTimerInstallOpts): this;
232
- useRealTimers(): this;
233
- runOnlyPendingTimers(): this;
234
- runOnlyPendingTimersAsync(): Promise<this>;
235
- runAllTimers(): this;
236
- runAllTimersAsync(): Promise<this>;
237
- runAllTicks(): this;
238
- advanceTimersByTime(ms: number): this;
239
- advanceTimersByTimeAsync(ms: number): Promise<this>;
240
- advanceTimersToNextTimer(): this;
241
- advanceTimersToNextTimerAsync(): Promise<this>;
234
+ /**
235
+ * This method wraps all further calls to timers until [`vi.useRealTimers()`](https://vitest.dev/api/vi#vi-userealtimers) is called.
236
+ */
237
+ useFakeTimers(config?: FakeTimerInstallOpts): VitestUtils;
238
+ /**
239
+ * Restores mocked timers to their original implementations. All timers that were scheduled before will be discarded.
240
+ */
241
+ useRealTimers(): VitestUtils;
242
+ /**
243
+ * This method will call every timer that was initiated after [`vi.useFakeTimers`](https://vitest.dev/api/vi#vi-usefaketimers) call.
244
+ * It will not fire any timer that was initiated during its call.
245
+ */
246
+ runOnlyPendingTimers(): VitestUtils;
247
+ /**
248
+ * This method will asynchronously call every timer that was initiated after [`vi.useFakeTimers`](https://vitest.dev/api/vi#vi-usefaketimers) call, even asynchronous ones.
249
+ * It will not fire any timer that was initiated during its call.
250
+ */
251
+ runOnlyPendingTimersAsync(): Promise<VitestUtils>;
252
+ /**
253
+ * This method will invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimers` will be fired.
254
+ * If you have an infinite interval, it will throw after 10,000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/#faketimers-looplimit)).
255
+ */
256
+ runAllTimers(): VitestUtils;
257
+ /**
258
+ * This method will asynchronously invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimersAsync` will be fired even asynchronous timers.
259
+ * If you have an infinite interval, it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/#faketimers-looplimit)).
260
+ */
261
+ runAllTimersAsync(): Promise<VitestUtils>;
262
+ /**
263
+ * Calls every microtask that was queued by `process.nextTick`. This will also run all microtasks scheduled by themselves.
264
+ */
265
+ runAllTicks(): VitestUtils;
266
+ /**
267
+ * This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first.
268
+ */
269
+ advanceTimersByTime(ms: number): VitestUtils;
270
+ /**
271
+ * This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first. This will include and await asynchronously set timers.
272
+ */
273
+ advanceTimersByTimeAsync(ms: number): Promise<VitestUtils>;
274
+ /**
275
+ * Will call next available timer. Useful to make assertions between each timer call. You can chain call it to manage timers by yourself.
276
+ */
277
+ advanceTimersToNextTimer(): VitestUtils;
278
+ /**
279
+ * Will call next available timer and wait until it's resolved if it was set asynchronously. Useful to make assertions between each timer call.
280
+ */
281
+ advanceTimersToNextTimerAsync(): Promise<VitestUtils>;
282
+ /**
283
+ * Get the number of waiting timers.
284
+ */
242
285
  getTimerCount(): number;
243
- setSystemTime(time: number | string | Date): this;
286
+ /**
287
+ * If fake timers are enabled, this method simulates a user changing the system clock (will affect date related API like `hrtime`, `performance.now` or `new Date()`) - however, it will not fire any timers.
288
+ * If fake timers are not enabled, this method will only mock `Date.*` and `new Date()` calls.
289
+ */
290
+ setSystemTime(time: number | string | Date): VitestUtils;
291
+ /**
292
+ * Returns mocked current date that was set using `setSystemTime`. If date is not mocked the method will return `null`.
293
+ */
244
294
  getMockedSystemTime(): Date | null;
295
+ /**
296
+ * When using `vi.useFakeTimers`, `Date.now` calls are mocked. If you need to get real time in milliseconds, you can call this function.
297
+ */
245
298
  getRealSystemTime(): number;
246
- clearAllTimers(): this;
299
+ /**
300
+ * Removes all timers that are scheduled to run. These timers will never run in the future.
301
+ */
302
+ clearAllTimers(): VitestUtils;
303
+ /**
304
+ * Creates a spy on a method or getter/setter of an object similar to [`vi.fn()`](https://vitest.dev/api/vi#vi-fn). It returns a [mock function](https://vitest.dev/api/mock).
305
+ *
306
+ * @example
307
+ * const cart = {
308
+ * getApples: () => 42
309
+ * }
310
+ *
311
+ * const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)
312
+ *
313
+ * expect(cart.getApples()).toBe(10)
314
+ * expect(spy).toHaveBeenCalled()
315
+ * expect(spy).toHaveReturnedWith(10)
316
+ */
247
317
  spyOn: typeof spyOn;
318
+ /**
319
+ * Creates a spy on a function, though can be initiated without one. Every time a function is invoked, it stores its call arguments, returns, and instances. Also, you can manipulate its behavior with [methods](https://vitest.dev/api/mock).
320
+ *
321
+ * If no function is given, mock will return `undefined`, when invoked.
322
+ *
323
+ * @example
324
+ * const getApples = vi.fn(() => 0)
325
+ *
326
+ * getApples()
327
+ *
328
+ * expect(getApples).toHaveBeenCalled()
329
+ * expect(getApples).toHaveReturnedWith(0)
330
+ *
331
+ * getApples.mockReturnValueOnce(5)
332
+ *
333
+ * expect(getApples()).toBe(5)
334
+ * expect(getApples).toHaveNthReturnedWith(2, 5)
335
+ */
248
336
  fn: typeof fn;
337
+ /**
338
+ * Wait for the callback to execute successfully. If the callback throws an error or returns a rejected promise it will continue to wait until it succeeds or times out.
339
+ *
340
+ * This is very useful when you need to wait for some asynchronous action to complete, for example, when you start a server and need to wait for it to start.
341
+ *
342
+ * @example
343
+ * const server = createServer()
344
+ *
345
+ * await vi.waitFor(
346
+ * () => {
347
+ * if (!server.isReady)
348
+ * throw new Error('Server not started')
349
+ *
350
+ * console.log('Server started')
351
+ * }, {
352
+ * timeout: 500, // default is 1000
353
+ * interval: 20, // default is 50
354
+ * }
355
+ * )
356
+ */
249
357
  waitFor: typeof waitFor;
358
+ /**
359
+ * This is similar to [`vi.waitFor`](https://vitest.dev/api/vi#vi-waitfor), but if the callback throws any errors, execution is immediately interrupted and an error message is received.
360
+ *
361
+ * If the callback returns a falsy value, the next check will continue until a truthy value is returned. This is useful when you need to wait for something to exist before taking the next step.
362
+ *
363
+ * @example
364
+ * const element = await vi.waitUntil(
365
+ * () => document.querySelector('.element'),
366
+ * {
367
+ * timeout: 500, // default is 1000
368
+ * interval: 20, // default is 50
369
+ * }
370
+ * )
371
+ *
372
+ * // do something with the element
373
+ * expect(element.querySelector('.element-child')).toBeTruthy()
374
+ */
250
375
  waitUntil: typeof waitUntil;
251
376
  /**
252
377
  * Run the factory before imports are evaluated. You can return a value from the factory
253
- * to reuse it inside your `vi.mock` factory and tests.
378
+ * to reuse it inside your [`vi.mock`](https://vitest.dev/api/vi#vi-mock) factory and tests.
379
+ *
380
+ * If used with [`vi.mock`](https://vitest.dev/api/vi#vi-mock), both will be hoisted in the order they are defined in.
254
381
  */
255
382
  hoisted<T>(factory: () => T): T;
256
383
  /**
257
- * Makes all `imports` to passed module to be mocked.
258
- * - If there is a factory, will return it's result. The call to `vi.mock` is hoisted to the top of the file,
259
- * so you don't have access to variables declared in the global file scope, if you didn't put them before imports!
260
- * - If `__mocks__` folder with file of the same name exist, all imports will
261
- * return it.
262
- * - If there is no `__mocks__` folder or a file with the same name inside, will call original
263
- * module and mock it.
264
- * @param path Path to the module. Can be aliased, if your config supports it
265
- * @param factory Factory for the mocked module. Has the highest priority.
384
+ * Mocks every import call to the module even if it was already statically imported.
385
+ *
386
+ * The call to `vi.mock` is hoisted to the top of the file, so you don't have access to variables declared in the global file scope
387
+ * unless they are defined with [`vi.hoisted`](https://vitest.dev/api/vi#vi-hoisted) before this call.
388
+ *
389
+ * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking#modules).
390
+ * @param path Path to the module. Can be aliased, if your Vitest config supports it
391
+ * @param factory Mocked module factory. The result of this function will be an exports object
266
392
  */
267
393
  mock(path: string, factory?: MockFactoryWithHelper): void;
268
394
  /**
269
- * Removes module from mocked registry. All subsequent calls to import will
270
- * return original module even if it was mocked.
271
- * @param path Path to the module. Can be aliased, if your config supports it
395
+ * Removes module from mocked registry. All calls to import will return the original module even if it was mocked before.
396
+ *
397
+ * This call is hoisted to the top of the file, so it will only unmock modules that were defined in `setupFiles`, for example.
398
+ * @param path Path to the module. Can be aliased, if your Vitest config supports it
272
399
  */
273
400
  unmock(path: string): void;
274
- doMock(path: string, factory?: () => any): void;
401
+ /**
402
+ * Mocks every subsequent [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) call.
403
+ *
404
+ * Unlike [`vi.mock`](https://vitest.dev/api/vi#vi-mock), this method will not mock statically imported modules because it is not hoisted to the top of the file.
405
+ *
406
+ * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking#modules).
407
+ * @param path Path to the module. Can be aliased, if your Vitest config supports it
408
+ * @param factory Mocked module factory. The result of this function will be an exports object
409
+ */
410
+ doMock(path: string, factory?: MockFactoryWithHelper): void;
411
+ /**
412
+ * Removes module from mocked registry. All subsequent calls to import will return original module.
413
+ *
414
+ * Unlike [`vi.unmock`](https://vitest.dev/api/vi#vi-unmock), this method is not hoisted to the top of the file.
415
+ * @param path Path to the module. Can be aliased, if your Vitest config supports it
416
+ */
275
417
  doUnmock(path: string): void;
276
418
  /**
277
419
  * Imports module, bypassing all checks if it should be mocked.
278
420
  * Can be useful if you want to mock module partially.
279
421
  * @example
280
- * vi.mock('./example', async () => {
281
- * const axios = await vi.importActual('./example')
422
+ * vi.mock('./example.js', async () => {
423
+ * const axios = await vi.importActual<typeof import('./example.js')>('./example.js')
282
424
  *
283
425
  * return { ...axios, get: vi.fn() }
284
426
  * })
285
427
  * @param path Path to the module. Can be aliased, if your config supports it
286
- * @returns Actual module without spies
287
428
  */
288
- importActual<T = unknown>(path: string): Promise<T>;
429
+ importActual<T = ESModuleExports>(path: string): Promise<T>;
289
430
  /**
290
431
  * Imports a module with all of its properties and nested properties mocked.
291
- * For the rules applied, see docs.
432
+ *
433
+ * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking#modules).
434
+ * @example
435
+ * const example = await vi.importMock<typeof import('./example.js')>('./example.js')
436
+ * example.calc.mockReturnValue(10)
437
+ * expect(example.calc()).toBe(10)
292
438
  * @param path Path to the module. Can be aliased, if your config supports it
293
439
  * @returns Fully mocked module
294
440
  */
295
- importMock<T>(path: string): Promise<MaybeMockedDeep<T>>;
441
+ importMock<T = ESModuleExports>(path: string): Promise<MaybeMockedDeep<T>>;
296
442
  /**
297
- * Type helpers for TypeScript. In reality just returns the object that was passed.
443
+ * Type helper for TypeScript. Just returns the object that was passed.
298
444
  *
299
- * When `partial` is `true` it will expect a `Partial<T>` as a return value.
445
+ * When `partial` is `true` it will expect a `Partial<T>` as a return value. By default, this will only make TypeScript believe that
446
+ * the first level values are mocked. You can pass down `{ deep: true }` as a second argument to tell TypeScript that the whole object is mocked, if it actually is.
300
447
  * @example
301
- * import example from './example'
302
- * vi.mock('./example')
303
- *
304
- * test('1+1 equals 2' async () => {
305
- * vi.mocked(example.calc).mockRestore()
448
+ * import example from './example.js'
449
+ * vi.mock('./example.js')
306
450
  *
307
- * const res = example.calc(1, '+', 1)
308
- *
309
- * expect(res).toBe(2)
451
+ * test('1 + 1 equals 10' async () => {
452
+ * vi.mocked(example.calc).mockReturnValue(10)
453
+ * expect(example.calc(1, '+', 1)).toBe(10)
310
454
  * })
311
455
  * @param item Anything that can be mocked
312
456
  * @param deep If the object is deeply mocked
@@ -331,30 +475,52 @@ interface VitestUtils {
331
475
  deep: true;
332
476
  }): MaybePartiallyMockedDeep<T>;
333
477
  mocked<T>(item: T): MaybeMocked<T>;
334
- isMockFunction(fn: any): fn is EnhancedSpy;
335
- clearAllMocks(): this;
336
- resetAllMocks(): this;
337
- restoreAllMocks(): this;
478
+ /**
479
+ * Checks that a given parameter is a mock function. If you are using TypeScript, it will also narrow down its type.
480
+ */
481
+ isMockFunction(fn: any): fn is MockInstance;
482
+ /**
483
+ * Calls [`.mockClear()`](https://vitest.dev/api/mock#mockclear) on every mocked function. This will only empty `.mock` state, it will not reset implementation.
484
+ *
485
+ * It is useful if you need to clean up mock between different assertions.
486
+ */
487
+ clearAllMocks(): VitestUtils;
488
+ /**
489
+ * Calls [`.mockReset()`](https://vitest.dev/api/mock#mockreset) on every mocked function. This will empty `.mock` state, reset "once" implementations and force the base implementation to return `undefined` when invoked.
490
+ *
491
+ * This is useful when you want to completely reset a mock to the default state.
492
+ */
493
+ resetAllMocks(): VitestUtils;
494
+ /**
495
+ * Calls [`.mockRestore()`](https://vitest.dev/api/mock#mockrestore) on every mocked function. This will restore all original implementations.
496
+ */
497
+ restoreAllMocks(): VitestUtils;
338
498
  /**
339
499
  * Makes value available on global namespace.
340
500
  * Useful, if you want to have global variables available, like `IntersectionObserver`.
341
501
  * You can return it back to original value with `vi.unstubAllGlobals`, or by enabling `unstubGlobals` config option.
342
502
  */
343
- stubGlobal(name: string | symbol | number, value: unknown): this;
503
+ stubGlobal(name: string | symbol | number, value: unknown): VitestUtils;
344
504
  /**
345
505
  * Changes the value of `import.meta.env` and `process.env`.
346
506
  * You can return it back to original value with `vi.unstubAllEnvs`, or by enabling `unstubEnvs` config option.
347
507
  */
348
- stubEnv(name: string, value: string): this;
508
+ stubEnv(name: string, value: string): VitestUtils;
349
509
  /**
350
510
  * Reset the value to original value that was available before first `vi.stubGlobal` was called.
351
511
  */
352
- unstubAllGlobals(): this;
512
+ unstubAllGlobals(): VitestUtils;
353
513
  /**
354
514
  * Reset environmental variables to the ones that were available before first `vi.stubEnv` was called.
355
515
  */
356
- unstubAllEnvs(): this;
357
- resetModules(): this;
516
+ unstubAllEnvs(): VitestUtils;
517
+ /**
518
+ * Resets modules registry by clearing the cache of all modules. This allows modules to be reevaluated when reimported.
519
+ * Top-level imports cannot be re-evaluated. Might be useful to isolate modules where local state conflicts between tests.
520
+ *
521
+ * This method does not reset mocks registry. To clear mocks registry, use [`vi.unmock`](https://vitest.dev/api/vi#vi-unmock) or [`vi.doUnmock`](https://vitest.dev/api/vi#vi-dounmock).
522
+ */
523
+ resetModules(): VitestUtils;
358
524
  /**
359
525
  * Wait for all imports to load. Useful, if you have a synchronous call that starts
360
526
  * importing a module that you cannot await otherwise.
@@ -373,9 +539,15 @@ interface VitestUtils {
373
539
  declare const vitest: VitestUtils;
374
540
  declare const vi: VitestUtils;
375
541
 
376
- declare function getRunningMode(): "watch" | "run";
542
+ declare function getRunningMode(): "run" | "watch";
377
543
  declare function isWatchMode(): boolean;
378
544
 
545
+ /**
546
+ * Gives access to injected context provided from the main thread.
547
+ * This usually returns a value provided by `globalSetup` or an external library.
548
+ */
549
+ declare function inject<T extends keyof ProvidedContext>(key: T): ProvidedContext[T];
550
+
379
551
  interface TransformResultWithSource extends TransformResult {
380
552
  source?: string;
381
553
  }
@@ -403,9 +575,10 @@ interface WebSocketHandlers {
403
575
  snapshotSaved(snapshot: SnapshotResult): void;
404
576
  rerun(files: string[]): Promise<void>;
405
577
  updateSnapshot(file?: File): Promise<void>;
578
+ getProvidedContext(): ProvidedContext;
406
579
  }
407
580
  interface WebSocketEvents extends Pick<Reporter, 'onCollected' | 'onFinished' | 'onTaskUpdate' | 'onUserConsoleLog' | 'onPathsCollected'> {
408
581
  onCancel(reason: CancelReason): void;
409
582
  }
410
583
 
411
- export { AfterSuiteRunMeta, type AssertType, type ExpectTypeOf, ModuleGraphData, Reporter, ResolvedConfig, RuntimeConfig, type TransformResultWithSource, UserConsoleLog, type VitestUtils, type WebSocketEvents, type WebSocketHandlers, assertType, createExpect, globalExpect as expect, expectTypeOf, getRunningMode, isFirstRun, isWatchMode, runOnce, vi, vitest };
584
+ export { AfterSuiteRunMeta, type AssertType, type ExpectTypeOf, ModuleGraphData, ProvidedContext, Reporter, ResolvedConfig, RuntimeConfig, type TransformResultWithSource, UserConsoleLog, type VitestUtils, type WebSocketEvents, type WebSocketHandlers, assertType, createExpect, globalExpect as expect, expectTypeOf, getRunningMode, inject, isFirstRun, isWatchMode, runOnce, vi, vitest };
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
1
  export { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, suite, test } from '@vitest/runner';
2
- export { b as bench } from './vendor-benchmark.44931cfa.js';
3
- export { i as isFirstRun, r as runOnce } from './vendor-run-once.3e5ef7d7.js';
4
- export { c as createExpect, a as expect, v as vi, b as vitest } from './vendor-vi.d30b47ae.js';
5
- import { d as dist } from './vendor-index.68ecee35.js';
6
- export { b as assertType, g as getRunningMode, a as isWatchMode } from './vendor-index.68ecee35.js';
2
+ export { b as bench } from './vendor-benchmark.b6befc50.js';
3
+ export { i as isFirstRun, r as runOnce } from './vendor-run-once.fb836747.js';
4
+ export { c as createExpect, a as expect, v as vi, b as vitest } from './vendor-vi.3baa7c4a.js';
5
+ import { d as dist } from './vendor-index.72df742e.js';
6
+ export { c as assertType, g as getRunningMode, a as inject, b as isWatchMode } from './vendor-index.72df742e.js';
7
7
  import * as chai from 'chai';
8
8
  export { chai };
9
9
  export { assert, should } from 'chai';
10
10
  import '@vitest/runner/utils';
11
11
  import '@vitest/utils';
12
- import './vendor-index.29282562.js';
12
+ import './vendor-index.2b92937b.js';
13
13
  import 'pathe';
14
14
  import 'std-env';
15
- import './vendor-global.97e4527c.js';
15
+ import './vendor-global.c3664e75.js';
16
16
  import './vendor-_commonjsHelpers.7d1333e8.js';
17
17
  import '@vitest/expect';
18
18
  import '@vitest/snapshot';
package/dist/node.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { V as VitestRunMode, U as UserConfig, e as Vitest, T as TestSequencer, W as WorkspaceSpec } from './reporters-1678fe04.js';
2
- export { i as BrowserProvider, h as BrowserProviderInitializationOptions, j as BrowserProviderOptions, g as TestSequencerConstructor, f as WorkspaceProject, s as startVitest } from './reporters-1678fe04.js';
1
+ import { V as VitestRunMode, U as UserConfig, e as Vitest, R as ResolvedConfig, f as ProvidedContext, T as TestSequencer, W as WorkspaceSpec } from './reporters-50c2bd49.js';
2
+ export { j as BrowserProvider, i as BrowserProviderInitializationOptions, k as BrowserProviderOptions, h as TestSequencerConstructor, g as WorkspaceProject, s as startVitest } from './reporters-50c2bd49.js';
3
3
  import { UserConfig as UserConfig$1, Plugin } from 'vite';
4
4
  import '@vitest/runner';
5
5
  import 'vite-node';
@@ -12,7 +12,6 @@ import 'vite-node/client';
12
12
  import '@vitest/snapshot/manager';
13
13
  import 'vite-node/server';
14
14
  import 'node:worker_threads';
15
- import 'rollup';
16
15
  import 'node:fs';
17
16
  import 'chai';
18
17
 
@@ -22,6 +21,11 @@ declare function VitestPlugin(options?: UserConfig, ctx?: Vitest): Promise<Plugi
22
21
 
23
22
  declare function registerConsoleShortcuts(ctx: Vitest): () => void;
24
23
 
24
+ interface GlobalSetupContext {
25
+ config: ResolvedConfig;
26
+ provide<T extends keyof ProvidedContext>(key: T, value: ProvidedContext[T]): void;
27
+ }
28
+
25
29
  declare class BaseSequencer implements TestSequencer {
26
30
  protected ctx: Vitest;
27
31
  constructor(ctx: Vitest);
@@ -31,4 +35,4 @@ declare class BaseSequencer implements TestSequencer {
31
35
 
32
36
  declare function ensurePackageInstalled(dependency: string, root: string): Promise<boolean>;
33
37
 
34
- export { BaseSequencer, TestSequencer, Vitest, VitestPlugin, WorkspaceSpec, createVitest, ensurePackageInstalled, registerConsoleShortcuts };
38
+ export { BaseSequencer, type GlobalSetupContext, TestSequencer, Vitest, VitestPlugin, WorkspaceSpec, createVitest, ensurePackageInstalled, registerConsoleShortcuts };
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- export { B as BaseSequencer, V as VitestPlugin, c as createVitest, e as ensurePackageInstalled, r as registerConsoleShortcuts, s as startVitest } from './vendor-node.327f8f1f.js';
1
+ export { B as BaseSequencer, V as VitestPlugin, c as createVitest, e as ensurePackageInstalled, r as registerConsoleShortcuts, s as startVitest } from './vendor-node.65461b16.js';
2
2
  import 'pathe';
3
3
  import 'vite';
4
4
  import 'node:path';
@@ -18,11 +18,11 @@ import 'vite-node/utils';
18
18
  import 'vite-node/client';
19
19
  import '@vitest/snapshot/manager';
20
20
  import 'vite-node/server';
21
- import './vendor-index.29282562.js';
21
+ import './vendor-index.2b92937b.js';
22
22
  import 'std-env';
23
23
  import '@vitest/runner/utils';
24
24
  import '@vitest/utils';
25
- import './vendor-global.97e4527c.js';
25
+ import './vendor-global.c3664e75.js';
26
26
  import './vendor-coverage.78040316.js';
27
27
  import './vendor-paths.84fc7a99.js';
28
28
  import 'node:v8';
@@ -46,7 +46,7 @@ import 'local-pkg';
46
46
  import 'module';
47
47
  import 'acorn';
48
48
  import 'acorn-walk';
49
- import './vendor-reporters.b9600369.js';
49
+ import './vendor-reporters.d24d80a4.js';
50
50
  import './chunk-runtime-console.f3263f87.js';
51
51
  import 'node:stream';
52
52
  import 'node:console';
@@ -12,7 +12,6 @@ import { ViteNodeRunner } from 'vite-node/client';
12
12
  import { SnapshotManager } from '@vitest/snapshot/manager';
13
13
  import { ViteNodeServer } from 'vite-node/server';
14
14
  import { MessagePort } from 'node:worker_threads';
15
- import * as rollup from 'rollup';
16
15
  import { Stats } from 'node:fs';
17
16
  import * as chai from 'chai';
18
17
 
@@ -497,18 +496,20 @@ declare class WorkspaceProject {
497
496
  closingPromise: Promise<unknown> | undefined;
498
497
  browserProvider: BrowserProvider | undefined;
499
498
  testFilesList: string[];
500
- private _globalSetupInit;
501
499
  private _globalSetups;
500
+ private _provided;
502
501
  constructor(path: string | number, ctx: Vitest);
503
502
  getName(): string;
504
503
  isCore(): boolean;
504
+ provide: (key: string, value: unknown) => void;
505
+ getProvidedContext(): ProvidedContext;
505
506
  initializeGlobalSetup(): Promise<void>;
506
507
  teardownGlobalSetup(): Promise<void>;
507
508
  get logger(): Logger;
508
509
  getModulesByFilepath(file: string): Set<vite.ModuleNode>;
509
510
  getModuleById(id: string): vite.ModuleNode | undefined;
510
- getSourceMapModuleById(id: string): rollup.SourceMap | null | undefined;
511
- getBrowserSourceMapModuleById(id: string): rollup.SourceMap | null | undefined;
511
+ getSourceMapModuleById(id: string): RawSourceMap | null | undefined;
512
+ getBrowserSourceMapModuleById(id: string): RawSourceMap | null | undefined;
512
513
  get reporters(): Reporter[];
513
514
  globTestFiles(filters?: string[]): Promise<string[]>;
514
515
  globAllTestFiles(config: ResolvedConfig, cwd: string): Promise<string[]>;
@@ -558,7 +559,7 @@ interface BrowserConfigOptions {
558
559
  *
559
560
  * @default 'webdriverio'
560
561
  */
561
- provider?: 'webdriverio' | 'playwright' | (string & {});
562
+ provider?: 'webdriverio' | 'playwright' | 'none' | (string & {});
562
563
  /**
563
564
  * Options that are passed down to a browser provider.
564
565
  * To support type hinting, add one of the types to your tsconfig.json "compilerOptions.types" field:
@@ -654,6 +655,8 @@ interface ModuleGraphData {
654
655
  inlined: string[];
655
656
  }
656
657
  type OnServerRestartHandler = (reason?: string) => Promise<void> | void;
658
+ interface ProvidedContext {
659
+ }
657
660
 
658
661
  declare class StateManager {
659
662
  filesMap: Map<string, File[]>;
@@ -1199,6 +1202,7 @@ interface ContextRPC {
1199
1202
  files: string[];
1200
1203
  invalidates?: string[];
1201
1204
  environment: ContextTestEnvironment;
1205
+ providedContext: Record<string, any>;
1202
1206
  }
1203
1207
 
1204
1208
  interface WorkerContext extends ContextRPC {
@@ -1223,6 +1227,7 @@ interface WorkerGlobalState {
1223
1227
  onCancel: Promise<CancelReason>;
1224
1228
  moduleCache: ModuleCacheMap;
1225
1229
  mockMap: MockMap;
1230
+ providedContext: Record<string, any>;
1226
1231
  durations: {
1227
1232
  environment: number;
1228
1233
  prepare: number;
@@ -1635,6 +1640,18 @@ interface WorkerContextOptions {
1635
1640
  * @default true
1636
1641
  */
1637
1642
  isolate?: boolean;
1643
+ /**
1644
+ * Pass additional arguments to `node` process when spawning `worker_threads` or `child_process`.
1645
+ *
1646
+ * See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
1647
+ *
1648
+ * Set to `process.execArgv` to pass all arguments of the current process.
1649
+ *
1650
+ * Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
1651
+ *
1652
+ * @default [] // no execution arguments are passed
1653
+ */
1654
+ execArgv?: string[];
1638
1655
  }
1639
1656
  interface VmOptions {
1640
1657
  /**
@@ -1644,6 +1661,18 @@ interface VmOptions {
1644
1661
  memoryLimit?: string | number;
1645
1662
  /** Isolation is always enabled */
1646
1663
  isolate?: true;
1664
+ /**
1665
+ * Pass additional arguments to `node` process when spawning `worker_threads` or `child_process`.
1666
+ *
1667
+ * See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
1668
+ *
1669
+ * Set to `process.execArgv` to pass all arguments of the current process.
1670
+ *
1671
+ * Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
1672
+ *
1673
+ * @default [] // no execution arguments are passed
1674
+ */
1675
+ execArgv?: string[];
1647
1676
  }
1648
1677
 
1649
1678
  type BuiltinEnvironment = 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime';
@@ -2184,6 +2213,10 @@ interface InlineConfig {
2184
2213
  * @default 0
2185
2214
  */
2186
2215
  retry?: number;
2216
+ /**
2217
+ * Show full diff when snapshot fails instead of a patch.
2218
+ */
2219
+ expandSnapshotDiff?: boolean;
2187
2220
  }
2188
2221
  interface TypecheckConfig {
2189
2222
  /**
@@ -2394,4 +2427,4 @@ type Context = RootAndTarget & {
2394
2427
  lastActivePath?: string;
2395
2428
  };
2396
2429
 
2397
- export { type WorkerRPC as $, type AfterSuiteRunMeta as A, type BaseCoverageOptions as B, type CoverageV8Options as C, type ApiConfig as D, type Environment as E, type FakeTimerInstallOpts as F, type EnvironmentOptions as G, type HappyDOMOptions as H, type DepsOptimizationOptions as I, type JSDOMOptions as J, type TransformModePatterns as K, type InlineConfig as L, type MockFactoryWithHelper as M, type TypecheckConfig as N, type RuntimeRPC as O, type ProjectConfig as P, type RunnerRPC as Q, type ResolvedConfig as R, type ContextTestEnvironment as S, type TestSequencer as T, type UserConfig as U, type VitestRunMode as V, type WorkspaceSpec as W, type ResolvedTestEnvironment as X, type ContextRPC as Y, type WorkerContext as Z, type ResolveIdFunction as _, type ResolvedCoverageOptions as a, type WorkerGlobalState as a0, type Awaitable as a1, type Nullable as a2, type Arrayable as a3, type ArgumentsType$1 as a4, type MutableArray as a5, type Constructable as a6, type ModuleCache as a7, type EnvironmentReturn as a8, type VmEnvironmentReturn as a9, type BenchmarkBuiltinReporters as aA, type OnServerRestartHandler as aa, type ReportContext as ab, type CoverageReporter as ac, type CoverageIstanbulOptions as ad, type CustomProviderOptions as ae, type BenchmarkUserOptions as af, type Benchmark as ag, type BenchmarkResult as ah, type BenchFunction as ai, type BenchmarkAPI as aj, type PendingSuiteMock as ak, type MockFactory as al, type MockMap as am, DefaultReporter as an, BasicReporter as ao, DotReporter as ap, JsonReporter$1 as aq, VerboseReporter as ar, TapReporter as as, JUnitReporter as at, TapFlatReporter as au, HangingProcessReporter as av, BaseReporter as aw, ReportersMap as ax, type BuiltinReporters as ay, BenchmarkReportsMap as az, type CoverageOptions as b, type CoverageProvider as c, type CoverageProviderModule as d, Vitest as e, WorkspaceProject as f, type TestSequencerConstructor as g, type BrowserProviderInitializationOptions as h, type BrowserProvider as i, type BrowserProviderOptions as j, type RuntimeConfig as k, type UserConsoleLog as l, type ModuleGraphData as m, type Reporter as n, type RawErrsMap as o, type TscErrorInfo as p, type CollectLineNumbers as q, type CollectLines as r, startVitest as s, type RootAndTarget as t, type Context as u, type Pool as v, type PoolOptions as w, type BuiltinEnvironment as x, type VitestEnvironment as y, type CSSModuleScopeStrategy as z };
2430
+ export { type ResolveIdFunction as $, type AfterSuiteRunMeta as A, type BaseCoverageOptions as B, type CoverageV8Options as C, type CSSModuleScopeStrategy as D, type Environment as E, type FakeTimerInstallOpts as F, type ApiConfig as G, type HappyDOMOptions as H, type EnvironmentOptions as I, type JSDOMOptions as J, type DepsOptimizationOptions as K, type TransformModePatterns as L, type MockFactoryWithHelper as M, type InlineConfig as N, type TypecheckConfig as O, type ProjectConfig as P, type RuntimeRPC as Q, type ResolvedConfig as R, type RunnerRPC as S, type TestSequencer as T, type UserConfig as U, type VitestRunMode as V, type WorkspaceSpec as W, type ContextTestEnvironment as X, type ResolvedTestEnvironment as Y, type ContextRPC as Z, type WorkerContext as _, type ResolvedCoverageOptions as a, type WorkerRPC as a0, type WorkerGlobalState as a1, type Awaitable as a2, type Nullable as a3, type Arrayable as a4, type ArgumentsType$1 as a5, type MutableArray as a6, type Constructable as a7, type ModuleCache as a8, type EnvironmentReturn as a9, BenchmarkReportsMap as aA, type BenchmarkBuiltinReporters as aB, type VmEnvironmentReturn as aa, type OnServerRestartHandler as ab, type ReportContext as ac, type CoverageReporter as ad, type CoverageIstanbulOptions as ae, type CustomProviderOptions as af, type BenchmarkUserOptions as ag, type Benchmark as ah, type BenchmarkResult as ai, type BenchFunction as aj, type BenchmarkAPI as ak, type PendingSuiteMock as al, type MockFactory as am, type MockMap as an, DefaultReporter as ao, BasicReporter as ap, DotReporter as aq, JsonReporter$1 as ar, VerboseReporter as as, TapReporter as at, JUnitReporter as au, TapFlatReporter as av, HangingProcessReporter as aw, BaseReporter as ax, ReportersMap as ay, type BuiltinReporters as az, type CoverageOptions as b, type CoverageProvider as c, type CoverageProviderModule as d, Vitest as e, type ProvidedContext as f, WorkspaceProject as g, type TestSequencerConstructor as h, type BrowserProviderInitializationOptions as i, type BrowserProvider as j, type BrowserProviderOptions as k, type RuntimeConfig as l, type UserConsoleLog as m, type ModuleGraphData as n, type Reporter as o, type RawErrsMap as p, type TscErrorInfo as q, type CollectLineNumbers as r, startVitest as s, type CollectLines as t, type RootAndTarget as u, type Context as v, type Pool as w, type PoolOptions as x, type BuiltinEnvironment as y, type VitestEnvironment as z };
@@ -1,4 +1,4 @@
1
- export { aw as BaseReporter, ao as BasicReporter, aA as BenchmarkBuiltinReporters, az as BenchmarkReportsMap, ay as BuiltinReporters, an as DefaultReporter, ap as DotReporter, av as HangingProcessReporter, at as JUnitReporter, aq as JsonReporter, n as Reporter, ax as ReportersMap, au as TapFlatReporter, as as TapReporter, ar as VerboseReporter } from './reporters-1678fe04.js';
1
+ export { ax as BaseReporter, ap as BasicReporter, aB as BenchmarkBuiltinReporters, aA as BenchmarkReportsMap, az as BuiltinReporters, ao as DefaultReporter, aq as DotReporter, aw as HangingProcessReporter, au as JUnitReporter, ar as JsonReporter, o as Reporter, ay as ReportersMap, av as TapFlatReporter, at as TapReporter, as as VerboseReporter } from './reporters-50c2bd49.js';
2
2
  import 'vite';
3
3
  import '@vitest/runner';
4
4
  import 'vite-node';
@@ -11,6 +11,5 @@ import 'vite-node/client';
11
11
  import '@vitest/snapshot/manager';
12
12
  import 'vite-node/server';
13
13
  import 'node:worker_threads';
14
- import 'rollup';
15
14
  import 'node:fs';
16
15
  import 'chai';