interface VitestUtils {
    fn: {
        <TArgs, R>(): Mock<TArgs, R>;
        <TArgs, R>(implementation): Mock<TArgs, R>;
    };
    spyOn: {
        <T, S>(obj, methodName, accessType): MockInstance<[], T[S]>;
        <T, G>(obj, methodName, accessType): MockInstance<[T[G]], void>;
        <T, M>(obj, methodName): Required<T>[M] extends (new (...args) => R) | ((...args) => infer R)
            ? MockInstance<A, R>
            : never;
    };
    waitFor: (<T>(callback, options?) => Promise<T>);
    waitUntil: (<T>(callback, options?) => Promise<Truthy<T>>);
    advanceTimersByTime(ms): VitestUtils;
    advanceTimersByTimeAsync(ms): Promise<VitestUtils>;
    advanceTimersToNextTimer(): VitestUtils;
    advanceTimersToNextTimerAsync(): Promise<VitestUtils>;
    clearAllMocks(): VitestUtils;
    clearAllTimers(): VitestUtils;
    doMock(path, factory?): void;
    doUnmock(path): void;
    dynamicImportSettled(): Promise<void>;
    getMockedSystemTime(): null | Date;
    getRealSystemTime(): number;
    getTimerCount(): number;
    hoisted<T>(factory): T;
    importActual<T>(path): Promise<T>;
    importMock<T>(path): Promise<MaybeMockedDeep<T>>;
    isFakeTimers(): boolean;
    isMockFunction(fn): fn is MockInstance<any[], any>;
    mock(path, factory?): void;
    mocked<T>(item, deep?): MaybeMocked<T>;
    mocked<T>(item, deep): MaybeMockedDeep<T>;
    mocked<T>(item, options): MaybeMocked<T>;
    mocked<T>(item, options): MaybeMockedDeep<T>;
    mocked<T>(item, options): MaybePartiallyMocked<T>;
    mocked<T>(item, options): MaybePartiallyMockedDeep<T>;
    mocked<T>(item): MaybeMocked<T>;
    resetAllMocks(): VitestUtils;
    resetConfig(): void;
    resetModules(): VitestUtils;
    restoreAllMocks(): VitestUtils;
    runAllTicks(): VitestUtils;
    runAllTimers(): VitestUtils;
    runAllTimersAsync(): Promise<VitestUtils>;
    runOnlyPendingTimers(): VitestUtils;
    runOnlyPendingTimersAsync(): Promise<VitestUtils>;
    setConfig(config): void;
    setSystemTime(time): VitestUtils;
    stubEnv(name, value): VitestUtils;
    stubGlobal(name, value): VitestUtils;
    unmock(path): void;
    unstubAllEnvs(): VitestUtils;
    unstubAllGlobals(): VitestUtils;
    useFakeTimers(config?): VitestUtils;
    useRealTimers(): VitestUtils;
}

Properties

fn: {
    <TArgs, R>(): Mock<TArgs, R>;
    <TArgs, R>(implementation): Mock<TArgs, R>;
}

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.

If no function is given, mock will return undefined, when invoked.

Type declaration

    • <TArgs, R>(): Mock<TArgs, R>
    • 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.

      If no function is given, mock will return undefined, when invoked.

      Type Parameters

      • TArgs extends any[] = any

      • R = any

      Returns Mock<TArgs, R>

      Example

      const getApples = vi.fn(() => 0)

      getApples()

      expect(getApples).toHaveBeenCalled()
      expect(getApples).toHaveReturnedWith(0)

      getApples.mockReturnValueOnce(5)

      expect(getApples()).toBe(5)
      expect(getApples).toHaveNthReturnedWith(2, 5)
    • <TArgs, R>(implementation): Mock<TArgs, R>
    • 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.

      If no function is given, mock will return undefined, when invoked.

      Type Parameters

      • TArgs extends any[] = any[]

      • R = any

      Parameters

      • implementation: ((...args) => R)
          • (...args): R
          • Parameters

            Returns R

      Returns Mock<TArgs, R>

      Example

      const getApples = vi.fn(() => 0)

      getApples()

      expect(getApples).toHaveBeenCalled()
      expect(getApples).toHaveReturnedWith(0)

      getApples.mockReturnValueOnce(5)

      expect(getApples()).toBe(5)
      expect(getApples).toHaveNthReturnedWith(2, 5)

Example

const getApples = vi.fn(() => 0)

getApples()

expect(getApples).toHaveBeenCalled()
expect(getApples).toHaveReturnedWith(0)

getApples.mockReturnValueOnce(5)

expect(getApples()).toBe(5)
expect(getApples).toHaveNthReturnedWith(2, 5)
spyOn: {
    <T, S>(obj, methodName, accessType): MockInstance<[], T[S]>;
    <T, G>(obj, methodName, accessType): MockInstance<[T[G]], void>;
    <T, M>(obj, methodName): Required<T>[M] extends (new (...args) => R) | ((...args) => infer R)
        ? MockInstance<A, R>
        : never;
}

Creates a spy on a method or getter/setter of an object similar to vi.fn(). It returns a mock function.

Type declaration

    • <T, S>(obj, methodName, accessType): MockInstance<[], T[S]>
    • Creates a spy on a method or getter/setter of an object similar to vi.fn(). It returns a mock function.

      Type Parameters

      • T

      • S extends string | symbol

      Parameters

      • obj: T
      • methodName: S
      • accessType: "get"

      Returns MockInstance<[], T[S]>

      Example

      const cart = {
      getApples: () => 42
      }

      const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)

      expect(cart.getApples()).toBe(10)
      expect(spy).toHaveBeenCalled()
      expect(spy).toHaveReturnedWith(10)
    • <T, G>(obj, methodName, accessType): MockInstance<[T[G]], void>
    • Creates a spy on a method or getter/setter of an object similar to vi.fn(). It returns a mock function.

      Type Parameters

      • T

      • G extends string | symbol

      Parameters

      • obj: T
      • methodName: G
      • accessType: "set"

      Returns MockInstance<[T[G]], void>

      Example

      const cart = {
      getApples: () => 42
      }

      const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)

      expect(cart.getApples()).toBe(10)
      expect(spy).toHaveBeenCalled()
      expect(spy).toHaveReturnedWith(10)
    • <T, M>(obj, methodName): Required<T>[M] extends (new (...args) => R) | ((...args) => infer R)
          ? MockInstance<A, R>
          : never
    • Creates a spy on a method or getter/setter of an object similar to vi.fn(). It returns a mock function.

      Type Parameters

      • T

      • M extends string | number | symbol

      Parameters

      • obj: T
      • methodName: M

      Returns Required<T>[M] extends (new (...args) => R) | ((...args) => infer R)
          ? MockInstance<A, R>
          : never

      Example

      const cart = {
      getApples: () => 42
      }

      const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)

      expect(cart.getApples()).toBe(10)
      expect(spy).toHaveBeenCalled()
      expect(spy).toHaveReturnedWith(10)

Example

const cart = {
getApples: () => 42
}

const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)

expect(cart.getApples()).toBe(10)
expect(spy).toHaveBeenCalled()
expect(spy).toHaveReturnedWith(10)
waitFor: (<T>(callback, options?) => Promise<T>)

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.

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.

Type declaration

    • <T>(callback, options?): Promise<T>
    • 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.

      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.

      Type Parameters

      • T

      Parameters

      • callback: WaitForCallback<T>
      • Optional options: number | WaitForOptions

      Returns Promise<T>

      Example

      const server = createServer()

      await vi.waitFor(
      () => {
      if (!server.isReady)
      throw new Error('Server not started')

      console.log('Server started')
      }, {
      timeout: 500, // default is 1000
      interval: 20, // default is 50
      }
      )

Example

const server = createServer()

await vi.waitFor(
() => {
if (!server.isReady)
throw new Error('Server not started')

console.log('Server started')
}, {
timeout: 500, // default is 1000
interval: 20, // default is 50
}
)
waitUntil: (<T>(callback, options?) => Promise<Truthy<T>>)

This is similar to vi.waitFor, but if the callback throws any errors, execution is immediately interrupted and an error message is received.

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.

Type declaration

    • <T>(callback, options?): Promise<Truthy<T>>
    • This is similar to vi.waitFor, but if the callback throws any errors, execution is immediately interrupted and an error message is received.

      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.

      Type Parameters

      • T

      Parameters

      • callback: WaitUntilCallback<T>
      • Optional options: number | WaitUntilOptions

      Returns Promise<Truthy<T>>

      Example

      const element = await vi.waitUntil(
      () => document.querySelector('.element'),
      {
      timeout: 500, // default is 1000
      interval: 20, // default is 50
      }
      )

      // do something with the element
      expect(element.querySelector('.element-child')).toBeTruthy()

Example

const element = await vi.waitUntil(
() => document.querySelector('.element'),
{
timeout: 500, // default is 1000
interval: 20, // default is 50
}
)

// do something with the element
expect(element.querySelector('.element-child')).toBeTruthy()

Methods

  • This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first.

    Parameters

    • ms: number

    Returns VitestUtils

  • 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.

    Parameters

    • ms: number

    Returns Promise<VitestUtils>

  • Will call next available timer. Useful to make assertions between each timer call. You can chain call it to manage timers by yourself.

    Returns VitestUtils

  • Will call next available timer and wait until it's resolved if it was set asynchronously. Useful to make assertions between each timer call.

    Returns Promise<VitestUtils>

  • Calls .mockClear() on every mocked function. This will only empty .mock state, it will not reset implementation.

    It is useful if you need to clean up mock between different assertions.

    Returns VitestUtils

  • Removes all timers that are scheduled to run. These timers will never run in the future.

    Returns VitestUtils

  • Mocks every subsequent dynamic import call.

    Unlike vi.mock, this method will not mock statically imported modules because it is not hoisted to the top of the file.

    Mocking algorithm is described in documentation.

    Parameters

    • path: string

      Path to the module. Can be aliased, if your Vitest config supports it

    • Optional factory: MockFactoryWithHelper

      Mocked module factory. The result of this function will be an exports object

    Returns void

  • Removes module from mocked registry. All subsequent calls to import will return original module.

    Unlike vi.unmock, this method is not hoisted to the top of the file.

    Parameters

    • path: string

      Path to the module. Can be aliased, if your Vitest config supports it

    Returns void

  • Wait for all imports to load. Useful, if you have a synchronous call that starts importing a module that you cannot await otherwise. Will also wait for new imports, started during the wait.

    Returns Promise<void>

  • Returns mocked current date that was set using setSystemTime. If date is not mocked the method will return null.

    Returns null | Date

  • When using vi.useFakeTimers, Date.now calls are mocked. If you need to get real time in milliseconds, you can call this function.

    Returns number

  • Get the number of waiting timers.

    Returns number

  • Run the factory before imports are evaluated. You can return a value from the factory to reuse it inside your vi.mock factory and tests.

    If used with vi.mock, both will be hoisted in the order they are defined in.

    Type Parameters

    • T

    Parameters

    • factory: (() => T)
        • (): T
        • Returns T

    Returns T

  • Imports module, bypassing all checks if it should be mocked. Can be useful if you want to mock module partially.

    Type Parameters

    • T = ESModuleExports

    Parameters

    • path: string

      Path to the module. Can be aliased, if your config supports it

    Returns Promise<T>

    Example

    vi.mock('./example.js', async () => {
    const axios = await vi.importActual<typeof import('./example.js')>('./example.js')

    return { ...axios, get: vi.fn() }
    })
  • Imports a module with all of its properties and nested properties mocked.

    Mocking algorithm is described in documentation.

    Type Parameters

    • T = ESModuleExports

    Parameters

    • path: string

      Path to the module. Can be aliased, if your config supports it

    Returns Promise<MaybeMockedDeep<T>>

    Fully mocked module

    Example

    const example = await vi.importMock<typeof import('./example.js')>('./example.js')
    example.calc.mockReturnValue(10)
    expect(example.calc()).toBe(10)
  • Checks if fake timers are enabled.

    Returns boolean

  • Checks that a given parameter is a mock function. If you are using TypeScript, it will also narrow down its type.

    Parameters

    • fn: any

    Returns fn is MockInstance<any[], any>

  • Mocks every import call to the module even if it was already statically imported.

    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 unless they are defined with vi.hoisted before this call.

    Mocking algorithm is described in documentation.

    Parameters

    • path: string

      Path to the module. Can be aliased, if your Vitest config supports it

    • Optional factory: MockFactoryWithHelper

      Mocked module factory. The result of this function will be an exports object

    Returns void

  • Type helper for TypeScript. Just returns the object that was passed.

    When partial is true it will expect a Partial<T> as a return value. By default, this will only make TypeScript believe that 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.

    Type Parameters

    • T

    Parameters

    • item: T

      Anything that can be mocked

    • Optional deep: false

      If the object is deeply mocked

    Returns MaybeMocked<T>

    Example

    import example from './example.js'
    vi.mock('./example.js')

    test('1 + 1 equals 10' async () => {
    vi.mocked(example.calc).mockReturnValue(10)
    expect(example.calc(1, '+', 1)).toBe(10)
    })
  • Type Parameters

    • T

    Parameters

    • item: T
    • deep: true

    Returns MaybeMockedDeep<T>

  • Type Parameters

    • T

    Parameters

    • item: T
    • options: {
          deep?: false;
          partial?: false;
      }
      • Optional deep?: false
      • Optional partial?: false

    Returns MaybeMocked<T>

  • Type Parameters

    • T

    Parameters

    • item: T
    • options: {
          deep: true;
          partial?: false;
      }
      • deep: true
      • Optional partial?: false

    Returns MaybeMockedDeep<T>

  • Type Parameters

    • T

    Parameters

    • item: T
    • options: {
          deep?: false;
          partial: true;
      }
      • Optional deep?: false
      • partial: true

    Returns MaybePartiallyMocked<T>

  • Type Parameters

    • T

    Parameters

    • item: T
    • options: {
          deep: true;
          partial: true;
      }
      • deep: true
      • partial: true

    Returns MaybePartiallyMockedDeep<T>

  • Type Parameters

    • T

    Parameters

    • item: T

    Returns MaybeMocked<T>

  • Calls .mockReset() on every mocked function. This will empty .mock state, reset "once" implementations and force the base implementation to return undefined when invoked.

    This is useful when you want to completely reset a mock to the default state.

    Returns VitestUtils

  • If config was changed with vi.setConfig, this will reset it to the original state.

    Returns void

  • Resets modules registry by clearing the cache of all modules. This allows modules to be reevaluated when reimported. Top-level imports cannot be re-evaluated. Might be useful to isolate modules where local state conflicts between tests.

    This method does not reset mocks registry. To clear mocks registry, use vi.unmock or vi.doUnmock.

    Returns VitestUtils

  • Calls .mockRestore() on every mocked function. This will restore all original implementations.

    Returns VitestUtils

  • Calls every microtask that was queued by process.nextTick. This will also run all microtasks scheduled by themselves.

    Returns VitestUtils

  • This method will invoke every initiated timer until the timer queue is empty. It means that every timer called during runAllTimers will be fired. If you have an infinite interval, it will throw after 10,000 tries (can be configured with fakeTimers.loopLimit).

    Returns VitestUtils

  • 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. If you have an infinite interval, it will throw after 10 000 tries (can be configured with fakeTimers.loopLimit).

    Returns Promise<VitestUtils>

  • This method will call every timer that was initiated after vi.useFakeTimers call. It will not fire any timer that was initiated during its call.

    Returns VitestUtils

  • This method will asynchronously call every timer that was initiated after vi.useFakeTimers call, even asynchronous ones. It will not fire any timer that was initiated during its call.

    Returns Promise<VitestUtils>

  • Updates runtime config. You can only change values that are used when executing tests.

    Parameters

    Returns void

  • 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. If fake timers are not enabled, this method will only mock Date.* and new Date() calls.

    Parameters

    • time: string | number | Date

    Returns VitestUtils

  • Changes the value of import.meta.env and process.env. You can return it back to original value with vi.unstubAllEnvs, or by enabling unstubEnvs config option.

    Parameters

    • name: string
    • value: string

    Returns VitestUtils

  • Makes value available on global namespace. Useful, if you want to have global variables available, like IntersectionObserver. You can return it back to original value with vi.unstubAllGlobals, or by enabling unstubGlobals config option.

    Parameters

    • name: string | number | symbol
    • value: unknown

    Returns VitestUtils

  • Removes module from mocked registry. All calls to import will return the original module even if it was mocked before.

    This call is hoisted to the top of the file, so it will only unmock modules that were defined in setupFiles, for example.

    Parameters

    • path: string

      Path to the module. Can be aliased, if your Vitest config supports it

    Returns void

  • Reset environmental variables to the ones that were available before first vi.stubEnv was called.

    Returns VitestUtils

  • Reset the value to original value that was available before first vi.stubGlobal was called.

    Returns VitestUtils

  • This method wraps all further calls to timers until vi.useRealTimers() is called.

    Parameters

    • Optional config: FakeTimerInstallOpts

    Returns VitestUtils

  • Restores mocked timers to their original implementations. All timers that were scheduled before will be discarded.

    Returns VitestUtils

Generated using TypeDoc