Sub topic 6
Mock Functions with vi.fn
This chapter assumes you can write tests with describe, it, and expect, and that you know how promises and async/await work. It covers mock functions created with vi.fn. Later chapters cover spying on existing methods and replacing whole modules.
What a mock function is
A mock function is a stand-in for a real function. It records every call made to it, including the arguments, the return value, and the this value. You pass it into the code under test in place of a real dependency, such as an email sender or a payment client. Afterward, you check how the code used it.
This lets you test one piece of code without running its dependencies. You also get to see how the code talks to those dependencies.
Creating, controlling, and inspecting mocks
Calling vi.fn() with no arguments gives you a mock that returns undefined. You can give it an implementation, or set return values for it, so it behaves the way the test needs.
// checkout.test.js
import { describe, it, expect, vi } from 'vitest'
function checkout(items, chargeCard) {
const total = items.reduce((sum, item) => sum + item.price, 0)
const receipt = chargeCard(total)
return receipt ? 'paid' : 'declined'
}
async function loadPrices(ids, fetchPrice) {
return Promise.all(ids.map((id) => fetchPrice(id)))
}
describe('vi.fn', () => {
it('records calls and arguments', () => {
const chargeCard = vi.fn(() => ({ id: 'r1' }))
const result = checkout([{ price: 5 }, { price: 7 }], chargeCard)
expect(result).toBe('paid')
expect(chargeCard).toHaveBeenCalledTimes(1)
expect(chargeCard).toHaveBeenCalledWith(12)
expect(chargeCard.mock.calls).toEqual([[12]])
expect(chargeCard.mock.results[0]).toEqual({ type: 'return', value: { id: 'r1' } })
})
it('returns different values per call', () => {
const chargeCard = vi.fn()
.mockReturnValueOnce(null)
.mockReturnValue({ id: 'r2' })
expect(checkout([{ price: 1 }], chargeCard)).toBe('declined')
expect(checkout([{ price: 1 }], chargeCard)).toBe('paid')
expect(chargeCard).toHaveBeenNthCalledWith(2, 1)
})
it('resolves promises with mockResolvedValue', async () => {
const fetchPrice = vi.fn().mockResolvedValue(10)
await expect(loadPrices(['a', 'b'], fetchPrice)).resolves.toEqual([10, 10])
expect(fetchPrice).toHaveBeenLastCalledWith('b', 1, ['a', 'b'])
})
})The last assertion shows a common surprise. ids.map(fetchPrice)-style callbacks receive the index and the array too, so the mock records three arguments, not one.
| API | Purpose |
|---|---|
| `vi.fn(impl)` | Create a mock with an implementation |
| `mockReturnValue(v)` / `mockReturnValueOnce(v)` | Set the return value for all calls, or for the next call only |
| `mockResolvedValue(v)` / `mockRejectedValue(e)` | Return a resolved or rejected promise |
| `mockImplementation(fn)` | Replace the implementation |
| `mock.calls` / `mock.results` | Raw records of arguments and outcomes |
| `mockClear()` | Erase the recorded calls and results |
| `mockReset()` | Erase the records and the implementations you configured |
Common errors
- Asserting on the wrong thing.
expect(chargeCard())calls the mock yourself. Pass the mock itself toexpect:expect(chargeCard).toHaveBeenCalled(). - Leaking state between tests. If you share a mock across tests, its call history keeps growing. Call
mockClear()in abeforeEach, or setclearMocks: truein your config. - The code never receives the mock. A
vi.fnonly gets used if the code under test is given it, for example as an argument. If the code imports its dependency directly, you needvi.mock, which a later chapter covers.
Exercise
A test creates const log = vi.fn() and calls ['x', 'y'].forEach(log). Which assertion passes: expect(log).toHaveBeenCalledWith('x') or expect(log).toHaveBeenCalledWith('x', 0, ['x', 'y'])? Why?
Show answer
The second one passes. forEach calls its callback with the element, the index, and the array, and toHaveBeenCalledWith must match every argument of at least one call. To check only the first argument, use expect(log.mock.calls[0][0]).toBe('x'), or pass (item) => log(item) to forEach.
Exercise
Write a mock fetchUser whose first call rejects with new Error('timeout') and whose later calls resolve with { name: 'Ada' }.
Show answer
const fetchUser = vi.fn().mockRejectedValueOnce(new Error('timeout')).mockResolvedValue({ name: 'Ada' })