Current context of the mock. It stores information about all invocation calls, instances, and results.
Returns current mock implementation if there is one.
If mock was created with vi.fn, it will consider passed down method as a mock implementation.
If mock was created with vi.spyOn, it will return undefined unless a custom implementation was provided.
Accepts a function that will be used as a mock implementation during the next call. Can be chained so that multiple function calls produce different results.
const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1);
expect(fn(3)).toBe(4);
expect(fn(3)).toBe(3);
Accepts a value that will be rejected during the next function call. If chained, every consecutive call will reject specified value.
const asyncMock = vi
.fn()
.mockResolvedValueOnce('first call')
.mockRejectedValueOnce(new Error('Async error'))
await asyncMock() // first call
await asyncMock() // throws "Async error"
Accepts a value that will be resolved during the next function call. If chained, every consecutive call will resolve specified value.
const myMockFn = vi
.fn()
.mockResolvedValue('default')
.mockResolvedValueOnce('first call')
.mockResolvedValueOnce('second call')
// Promise<'first call'>, Promise<'second call'>, Promise<'default'>
console.log(myMockFn(), myMockFn(), myMockFn())
Accepts a value that will be returned whenever the mock function is called.
Accepts a value that will be returned during the next function call. If chained, every consecutive call will return the specified value.
When there are no more mockReturnValueOnce values to use, mock will fallback to the previously defined implementation if there is one.
const myMockFn = vi
.fn()
.mockReturnValue('default')
.mockReturnValueOnce('first call')
.mockReturnValueOnce('second call')
// 'first call', 'second call', 'default'
console.log(myMockFn(), myMockFn(), myMockFn())
Overrides the original mock implementation temporarily while the callback is being executed.
const myMockFn = vi.fn(() => 'original')
myMockFn.withImplementation(() => 'temp', () => {
myMockFn() // 'temp'
})
myMockFn() // 'original'
Generated using TypeDoc
Deprecated
Use MockInstance<A, R> instead