Sub topic 6
Mock Functions with vi.fn
This chapter assumes you can already write tests with describe, it, and expect, and that you know how to test promises with await and .rejects. It also assumes you are comfortable with ES modules and async/await. Spying on existing methods (vi.spyOn) and replacing whole modules (vi.mock) have their own chapters. Here the focus is the building block both of them depend on: the mock function created by vi.fn.
What a mock function is
A mock function is a stand-in for a real function. It does two jobs:
- It records every call: the arguments, the return value or thrown error, and the
thisvalue. - It behaves however the test tells it to: it can return a fixed value, resolve a promise, throw, or run a custom implementation.
You use one when the code under test receives a function as a dependency, such as a callback, an event handler, or an injected service like charge or sendEmail. The real dependency might be slow, might cost money, or might be hard to observe. The mock lets the test control what goes in and check what came out.
import { it, expect, vi } from 'vitest'
it('a bare mock returns undefined and records calls', () => {
const fn = vi.fn()
const result = fn('a', 1)
expect(result).toBeUndefined()
expect(fn).toHaveBeenCalledWith('a', 1)
expect(fn.mock.calls).toEqual([['a', 1]])
})A worked example: injected dependencies
The function below takes its side effects as parameters. This design is what makes vi.fn the natural tool, because no module mocking is needed.
// checkout.js
export async function checkout(cart, { charge, notify }) {
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0)
if (total === 0) {
return { status: 'empty' }
}
try {
const receipt = await charge(total)
notify(`Charged ${total}`)
return { status: 'paid', id: receipt.id }
} catch (err) {
notify(`Payment failed: ${err.message}`)
return { status: 'failed' }
}
}// checkout.test.js
import { describe, it, expect, vi } from 'vitest'
import { checkout } from './checkout.js'
const cart = [
{ price: 10, qty: 2 },
{ price: 5, qty: 1 },
]
describe('checkout', () => {
it('charges the total and notifies on success', async () => {
const charge = vi.fn().mockResolvedValue({ id: 'r_1' })
const notify = vi.fn()
const result = await checkout(cart, { charge, notify })
expect(result).toEqual({ status: 'paid', id: 'r_1' })
expect(charge).toHaveBeenCalledTimes(1)
expect(charge).toHaveBeenCalledWith(25)
expect(notify).toHaveBeenCalledWith('Charged 25')
})
it('reports a failed payment', async () => {
const charge = vi.fn().mockRejectedValue(new Error('card declined'))
const notify = vi.fn()
const result = await checkout(cart, { charge, notify })
expect(result).toEqual({ status: 'failed' })
expect(notify).toHaveBeenCalledWith('Payment failed: card declined')
})
it('does not charge an empty cart', async () => {
const charge = vi.fn()
const notify = vi.fn()
const result = await checkout([], { charge, notify })
expect(result).toEqual({ status: 'empty' })
expect(charge).not.toHaveBeenCalled()
expect(notify).not.toHaveBeenCalled()
})
})Each test creates fresh mocks, so no recorded calls leak from one test into the next. This is the simplest way to keep tests isolated.
Controlling behavior
All of these methods return the mock itself, so you can chain them right after vi.fn().
| Method | Effect |
|---|---|
| `vi.fn(impl)` | Uses `impl` as the implementation |
| `mockImplementation(fn)` | Replaces the implementation for all later calls |
| `mockImplementationOnce(fn)` | Uses `fn` for the next call only |
| `mockReturnValue(v)` | Always returns `v` |
| `mockReturnValueOnce(v)` | Returns `v` on the next call only |
| `mockResolvedValue(v)` | Returns `Promise.resolve(v)` |
| `mockResolvedValueOnce(v)` | Resolves `v` on the next call only |
| `mockRejectedValue(e)` | Returns `Promise.reject(e)` |
| `mockRejectedValueOnce(e)` | Rejects with `e` on the next call only |
The "once" values form a queue. Each call takes the next queued value. When the queue is empty, the mock falls back to its default implementation. That pattern fits retry logic well:
import { it, expect, vi } from 'vitest'
async function withRetry(task, attempts) {
let lastError
for (let i = 0; i < attempts; i++) {
try {
return await task()
} catch (err) {
lastError = err
}
}
throw lastError
}
it('succeeds on the third attempt', async () => {
const task = vi
.fn()
.mockRejectedValueOnce(new Error('timeout'))
.mockRejectedValueOnce(new Error('timeout'))
.mockResolvedValue('ok')
await expect(withRetry(task, 3)).resolves.toBe('ok')
expect(task).toHaveBeenCalledTimes(3)
})
it('gives up after the allowed attempts', async () => {
const task = vi.fn().mockRejectedValue(new Error('down'))
await expect(withRetry(task, 2)).rejects.toThrow('down')
expect(task).toHaveBeenCalledTimes(2)
})Inspecting calls
The matchers cover most needs:
| Matcher | Passes when |
|---|---|
| `toHaveBeenCalled()` | Called at least once |
| `toHaveBeenCalledTimes(n)` | Called exactly `n` times |
| `toHaveBeenCalledWith(...args)` | Any call matched these arguments |
| `toHaveBeenLastCalledWith(...args)` | The most recent call matched |
| `toHaveBeenNthCalledWith(n, ...args)` | The `n`th call (1-based) matched |
| `toHaveReturnedWith(v)` | Any call returned `v` |
Arguments are compared by deep equality, the same way toEqual compares values. You can also pass asymmetric matchers when only part of an argument matters:
import { it, expect, vi } from 'vitest'
it('matches arguments loosely', () => {
const track = vi.fn()
track('signup', { userId: 7, at: Date.now(), source: 'ad' })
expect(track).toHaveBeenCalledWith(
'signup',
expect.objectContaining({ userId: 7, at: expect.any(Number) }),
)
})When the matchers cannot express what you need, read the raw records on fn.mock:
mock.calls: an array with one array of arguments per call.mock.lastCall: the arguments of the most recent call.mock.results: one{ type, value }entry per call, wheretypeis'return'or'throw'.mock.settledResults: for async mocks, the resolved or rejected value of each returned promise.mock.instancesandmock.contexts: thethisvalues, which matter when the mock is called withnewor as a method.
import { it, expect, vi } from 'vitest'
it('records returns and throws', () => {
const parse = vi.fn((text) => JSON.parse(text))
parse('{"a":1}')
expect(() => parse('not json')).toThrow()
expect(parse.mock.results[0]).toEqual({ type: 'return', value: { a: 1 } })
expect(parse.mock.results[1].type).toBe('throw')
})Clearing, resetting, and restoring
A mock created at module or describe scope and shared across tests keeps accumulating calls. Vitest gives you three levels of cleanup:
| Method | Clears recorded calls | Drops queued "once" values and custom implementation |
|---|---|---|
| `mockClear()` | Yes | No |
| `mockReset()` | Yes | Yes |
| `mockRestore()` | Yes | Yes, and for spies puts the original method back |
In Vitest 3, mockReset() on vi.fn(impl) goes back to impl. On a bare vi.fn() it goes back to an empty function that returns undefined. Earlier major versions always reset to the empty function, so check your version if a reset mock behaves unexpectedly. mockRestore matters most for spies, which the next chapter covers.
To apply cleanup to every mock at once, call vi.clearAllMocks() or vi.resetAllMocks() in an afterEach hook. You can also set clearMocks: true or mockReset: true in the test section of your config, which the configuration chapter covers.
Common errors and gotchas
Recorded arguments are references
mock.calls stores the arguments themselves, not copies. If the code mutates an object after passing it, the recorded call changes too:
import { it, expect, vi } from 'vitest'
it('sees the mutated object, not the original', () => {
const save = vi.fn()
const options = { retries: 1 }
save(options)
options.retries = 5
expect(save).toHaveBeenCalledWith({ retries: 5 })
})If you need the value as it was at call time, copy it inside an implementation: vi.fn((o) => { seen.push({ ...o }) }).
Forgetting that a bare mock returns undefined
When code does await charge(total) and then reads receipt.id, a bare vi.fn() resolves to undefined and the code throws a TypeError. The error shows up far from the real cause. Give every mock whose return value gets used an explicit return value.
Asserting with the wrong matcher
toHaveBeenCalledWith passes if any call matched. To check the order of calls, use toHaveBeenNthCalledWith. To prove there were no extra calls, add toHaveBeenCalledTimes. You can also compare the whole history at once with expect(fn.mock.calls).toEqual([...]).
Over-specifying
Asserting every argument of every call ties the test to implementation details. Assert the interactions that are part of the contract, such as "charged 25" and "never charged an empty cart", and skip incidental ones.
Exercises
Exercise
A mock is created with const fn = vi.fn().mockReturnValueOnce('a').mockReturnValue('z'). What do the first three calls return, and what do they return after fn.mockClear() and then after fn.mockReset()?
Show answer
The first three calls return 'a', 'z', 'z'. mockClear only empties mock.calls and mock.results, so later calls still return 'z'. mockReset also removes the configured behavior, so later calls return undefined, because this mock was created with a bare vi.fn() and has no original implementation.
Exercise
Write a test for function forEachPositive(nums, cb) { nums.filter((n) => n > 0).forEach((n, i) => cb(n, i)) } that proves the callback received exactly (3, 0) then (7, 1) for the input [3, -2, 7].
Show answer
const cb = vi.fn(); forEachPositive([3, -2, 7], cb); expect(cb.mock.calls).toEqual([[3, 0], [7, 1]]). Comparing mock.calls with toEqual checks the arguments, the order, and the number of calls in one assertion. Alternatively use toHaveBeenCalledTimes(2) together with toHaveBeenNthCalledWith(1, 3, 0) and toHaveBeenNthCalledWith(2, 7, 1).
Exercise
A test passes the object { id: 1 } to a mock, the code under test later sets id to 2, and expect(fn).toHaveBeenCalledWith({ id: 1 }) fails. Why, and how can the test capture the original value?
Show answer
mock.calls stores a reference to the same object, so the assertion sees the mutated value { id: 2 }. Capture a copy at call time with an implementation, for example const seen = []; const fn = vi.fn((o) => { seen.push({ ...o }) }), and then assert expect(seen[0]).toEqual({ id: 1 }).