Sub topic 7
Spying on Existing Methods with vi.spyOn
This chapter assumes you have read the earlier chapters on vi.fn and lifecycle hooks. You should be comfortable with toHaveBeenCalledWith, mockImplementation, mockReturnValue, and afterEach. It also assumes you can read ES module syntax and JavaScript classes.
A mock function made with vi.fn is a new function. You pass it in where a dependency is expected. Code doesn't always accept its dependencies that way, though. It may call Math.random, console.error, a method on a shared object, or a method on a class prototype. In those cases nothing gets passed in, so there is no parameter to swap. vi.spyOn covers this situation. It puts a mock function on an existing object property, records every call, and lets you put the original back afterwards.
How vi.spyOn Works Internally
vi.spyOn(object, methodName) does three things:
- It reads the current value of
object[methodName]and keeps it as the original. - It creates a mock function whose default implementation calls that original with the same
thisand arguments. - It redefines the property on the object so the spy sits where the original used to be.
The spy is a full mock, so it has the same .mock.calls and .mock.results and the same mockImplementation family of methods that you used with vi.fn. The difference is the default behavior. A bare vi.fn() returns undefined. A fresh spy calls through to the real method, so behavior stays the same until you choose to change it.
Observing Without Changing Behavior
Use a call-through spy when the real method is safe and fast to run, and you only want to check how it was used.
import { it, expect, vi, afterEach } from 'vitest'
const cart = {
items: [],
add(item) {
this.items.push(item)
return this.items.length
},
}
afterEach(() => {
vi.restoreAllMocks()
cart.items = []
})
it('records calls while the real method still runs', () => {
const spy = vi.spyOn(cart, 'add')
const count = cart.add('apple')
expect(count).toBe(1)
expect(cart.items).toEqual(['apple'])
expect(spy).toHaveBeenCalledWith('apple')
expect(spy).toHaveReturnedWith(1)
})The original method still gets this bound to cart, so this.items works. The test checks both the real side effect (cart.items) and the interaction (toHaveBeenCalledWith).
Replacing the Implementation
Calling the original isn't always what you want. It may be random, slow, noisy, or have side effects. Every method you know from vi.fn works on a spy:
import { describe, it, expect, vi, afterEach } from 'vitest'
function rollDie() {
return Math.floor(Math.random() * 6) + 1
}
function parseConfig(text) {
try {
return JSON.parse(text)
} catch (error) {
console.error('Invalid config:', error.message)
return {}
}
}
describe('replacing implementations', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('makes Math.random deterministic', () => {
vi.spyOn(Math, 'random').mockReturnValue(0.99)
expect(rollDie()).toBe(6)
})
it('returns a sequence of values', () => {
vi.spyOn(Math, 'random')
.mockReturnValueOnce(0)
.mockReturnValueOnce(0.5)
expect(rollDie()).toBe(1)
expect(rollDie()).toBe(4)
})
it('silences and checks console.error', () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(parseConfig('{not json')).toEqual({})
expect(errorSpy).toHaveBeenCalledTimes(1)
expect(errorSpy.mock.calls[0][0]).toBe('Invalid config:')
})
})Once the Once values run out, the spy goes back to its default implementation. For a spy, that default is the original method. In the second test, a third call to rollDie() would use the real Math.random again.
Restoring the Original
A spy changes a shared object. Math, console, and module-level singletons all live for the whole test file, and sometimes for the whole worker. If you don't restore a spy, the next test sees a mocked method it never asked for. This is one of the most common causes of tests that pass alone and fail together.
import { it, expect, vi } from 'vitest'
it('mockRestore puts the original method back', () => {
const original = Math.max
const spy = vi.spyOn(Math, 'max').mockReturnValue(0)
expect(Math.max(1, 2)).toBe(0)
spy.mockRestore()
expect(Math.max(1, 2)).toBe(2)
expect(Math.max).toBe(original)
})The three reset methods do different things:
| Method | Clears recorded calls | Removes custom implementation | Puts original property back on the object |
|---|---|---|---|
| `mockClear()` | Yes | No | No |
| `mockReset()` | Yes | Yes | No |
| `mockRestore()` | Yes | Yes | Yes |
vi.clearAllMocks(), vi.resetAllMocks(), and vi.restoreAllMocks() apply the matching operation to every mock. Calling vi.restoreAllMocks() in afterEach is the usual pattern. You can also set restoreMocks: true in the test section of your config so Vitest restores mocks before each test for you.
Spying on Class Instances Through the Prototype
When the code under test creates its own instances, you can't reach those objects to spy on them. Spy on the prototype instead. Every instance shares the prototype, so every instance uses the spy.
import { it, expect, vi, afterEach } from 'vitest'
class Account {
constructor(balance) {
this.balance = balance
}
withdraw(amount) {
if (amount > this.balance) {
throw new Error('Insufficient funds')
}
this.balance -= amount
}
}
function chargeAll(balances, amount) {
const accounts = balances.map((b) => new Account(b))
accounts.forEach((account) => account.withdraw(amount))
return accounts.map((account) => account.balance)
}
afterEach(() => {
vi.restoreAllMocks()
})
it('charges every account it creates', () => {
const spy = vi.spyOn(Account.prototype, 'withdraw')
expect(chargeAll([50, 80], 20)).toEqual([30, 60])
expect(spy).toHaveBeenCalledTimes(2)
expect(spy).toHaveBeenCalledWith(20)
expect(spy.mock.contexts[0].balance).toBe(30)
})spy.mock.contexts stores the this value of each call, so you can check which instance received it. A spy on the prototype doesn't help with methods defined as arrow-function class fields (withdraw = () => {}). Those are created on each instance and never live on the prototype.
Spying on Getters and Setters
Accessor properties need a third argument, 'get' or 'set':
import { it, expect, vi, afterEach } from 'vitest'
const settings = {
get theme() {
return 'light'
},
}
function headerClass() {
return settings.theme === 'dark' ? 'header-dark' : 'header-light'
}
afterEach(() => {
vi.restoreAllMocks()
})
it('overrides a getter', () => {
const spy = vi.spyOn(settings, 'theme', 'get').mockReturnValue('dark')
expect(headerClass()).toBe('header-dark')
expect(spy).toHaveBeenCalled()
})If you leave out 'get', Vitest tries to spy on the property's value, which is a string. The call fails because theme isn't a method.
Failure Modes
A spy only intercepts calls that look the method up on the object after the spy is installed. Most spy confusion comes from this rule.
Saved References Bypass the Spy
import { it, expect, vi } from 'vitest'
const formatter = {
shout(text) {
return text.toUpperCase()
},
}
it('a reference saved before spying skips the spy', () => {
const savedShout = formatter.shout
const spy = vi.spyOn(formatter, 'shout').mockReturnValue('mocked')
expect(savedShout('hi')).toBe('HI')
expect(formatter.shout('hi')).toBe('mocked')
expect(spy).toHaveBeenCalledTimes(1)
spy.mockRestore()
})Production code runs into the same thing when it destructures (const { shout } = formatter) or binds a method at module load time. The spy replaces the property on the object, but the earlier reference still points at the original function.
ES Module Exports
An ES module namespace object (import * as api from './api.js') has read-only, non-configurable bindings under the spec. Whether vi.spyOn(api, 'fetchUser') works depends on how Vite transformed the module, and it can fail with "Cannot redefine property" or a similar error. Even when it succeeds, functions inside api.js that call fetchUser use the local binding, not the export, so the spy never sees those calls. To replace a module export, use vi.mock, which the next chapter covers.
Properties That Can't Be Redefined
vi.spyOn fails on non-configurable properties, on frozen objects, and when the property doesn't exist yet. It throws instead of quietly doing nothing, so the error points you at the cause.
Choosing Between vi.fn and vi.spyOn
| Situation | Use |
|---|---|
| The dependency is passed in as an argument or option | `vi.fn` |
| The code calls a method on a global or shared object | `vi.spyOn` |
| You want to observe calls while keeping real behavior | `vi.spyOn` (call-through) |
| The code creates instances of a class itself | `vi.spyOn` on the prototype |
| The code imports a function from another module | `vi.mock` |
If you can pass a vi.fn in, prefer it. It touches no shared state, so it needs no cleanup and can't leak into other tests.
Exercise
A test calls vi.spyOn(Date, 'now').mockReturnValue(0) and has no afterEach cleanup. A later test in the same file checks that a timestamp is greater than zero and fails. Explain why, and give two ways to fix it.
Show answer
The spy replaced Date.now on the shared global Date object, and nothing restored it, so the later test still gets 0. One fix is to add afterEach(() => { vi.restoreAllMocks() }). Another is to set restoreMocks: true in the test section of the Vitest config. You can also call spy.mockRestore() at the end of the first test, but if an assertion fails before that line, the restore never runs.
Exercise
A module defines export const service = { load() { return 'real' } } and export const run = service.load. A test calls vi.spyOn(service, 'load').mockReturnValue('fake'), then asserts that run() returns 'fake'. The assertion fails. Why, and how should the code or the test change?
Show answer
run holds a reference to the original load function, taken when the module loaded and before the spy existed. The spy replaced only the service.load property, so run() still calls the original. Change the module so it looks the method up at call time, for example export const run = () => service.load(). Then the spy intercepts the call.