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.
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)
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.
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)
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)
Creates a spy on a method or getter/setter of an object similar to vi.fn(). It returns a mock function.
Creates a spy on a method or getter/setter of an object similar to vi.fn(). It returns a mock function.
const cart = {
getApples: () => 42
}
const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)
expect(cart.getApples()).toBe(10)
expect(spy).toHaveBeenCalled()
expect(spy).toHaveReturnedWith(10)
Creates a spy on a method or getter/setter of an object similar to vi.fn(). It returns a mock function.
const cart = {
getApples: () => 42
}
const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)
expect(cart.getApples()).toBe(10)
expect(spy).toHaveBeenCalled()
expect(spy).toHaveReturnedWith(10)
Creates a spy on a method or getter/setter of an object similar to vi.fn(). It returns a mock function.
const cart = {
getApples: () => 42
}
const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)
expect(cart.getApples()).toBe(10)
expect(spy).toHaveBeenCalled()
expect(spy).toHaveReturnedWith(10)
const cart = {
getApples: () => 42
}
const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)
expect(cart.getApples()).toBe(10)
expect(spy).toHaveBeenCalled()
expect(spy).toHaveReturnedWith(10)
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.
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.
Optional options: number | WaitForOptionsconst 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
}
)
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
}
)
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.
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.
Optional options: number | WaitUntilOptionsconst 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()
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()
This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first.
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.
Will call next available timer. Useful to make assertions between each timer call. You can chain call it to manage timers by yourself.
Will call next available timer and wait until it's resolved if it was set asynchronously. Useful to make assertions between each timer call.
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.
Removes all timers that are scheduled to run. These timers will never run in the future.
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.
Path to the module. Can be aliased, if your Vitest config supports it
Optional factory: MockFactoryWithHelperMocked module factory. The result of this function will be an exports object
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.
Path to the module. Can be aliased, if your Vitest config supports it
Imports module, bypassing all checks if it should be mocked. Can be useful if you want to mock module partially.
Path to the module. Can be aliased, if your config supports it
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.
Path to the module. Can be aliased, if your config supports it
Fully mocked module
const example = await vi.importMock<typeof import('./example.js')>('./example.js')
example.calc.mockReturnValue(10)
expect(example.calc()).toBe(10)
Checks that a given parameter is a mock function. If you are using TypeScript, it will also narrow down its type.
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.
Path to the module. Can be aliased, if your Vitest config supports it
Optional factory: MockFactoryWithHelperMocked module factory. The result of this function will be an exports object
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.
Anything that can be mocked
Optional deep: falseIf the object is deeply mocked
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)
})
Optional deep?: falseOptional partial?: falseOptional partial?: falseOptional deep?: falseCalls .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.
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.
Calls .mockRestore() on every mocked function. This will restore all original implementations.
Calls every microtask that was queued by process.nextTick. This will also run all microtasks scheduled by themselves.
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).
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).
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.
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.
Updates runtime config. You can only change values that are used when executing tests.
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.
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.
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.
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.
Path to the module. Can be aliased, if your Vitest config supports it
Reset environmental variables to the ones that were available before first vi.stubEnv was called.
Reset the value to original value that was available before first vi.stubGlobal was called.
This method wraps all further calls to timers until vi.useRealTimers() is called.
Optional config: FakeTimerInstallOptsRestores mocked timers to their original implementations. All timers that were scheduled before will be discarded.
Generated using TypeDoc
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.