Sub topic 7
Spying on Existing Methods with vi.spyOn
This chapter assumes you can write tests with describe, it, and expect, that you know how vi.fn records calls, and that you have used afterEach hooks. A spy builds on all three.
What a spy is
vi.fn creates a new function that you pass into your code. Sometimes you can't pass anything in, because the code calls a method on an object it already holds, such as console.warn, Math.random, or a method on a service object. vi.spyOn(object, 'methodName') replaces that method on the object with a mock function that wraps the original. The spy records every call, just like vi.fn, and you assert on it with the same matchers.
By default, a spy calls through to the original method. You add mockImplementation or mockReturnValue when you want to replace the original behavior.
Observing and replacing behavior
// cart.test.js
import { describe, it, expect, vi, afterEach } from 'vitest'
const pricing = {
taxRate() {
return 0.2
},
total(amount) {
return amount + amount * this.taxRate()
},
}
describe('pricing spies', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('calls through to the original by default', () => {
const spy = vi.spyOn(pricing, 'taxRate')
expect(pricing.total(100)).toBe(120)
expect(spy).toHaveBeenCalledTimes(1)
})
it('replaces the result when told to', () => {
vi.spyOn(pricing, 'taxRate').mockReturnValue(0)
expect(pricing.total(100)).toBe(100)
})
it('silences console output', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
console.warn('disk almost full')
expect(warn).toHaveBeenCalledWith('disk almost full')
})
it('sees the original again after restore', () => {
expect(pricing.taxRate()).toBe(0.2)
})
})The last test passes only because vi.restoreAllMocks() ran in afterEach. Without it, the mockReturnValue(0) from the second test would carry over into later tests that use pricing.
Restoring spies
| Call | Effect on a spy |
|---|---|
| `spy.mockClear()` | Clears recorded calls and keeps the current implementation |
| `spy.mockReset()` | Clears calls and resets the implementation |
| `spy.mockRestore()` | Puts the original method back on the object |
| `vi.restoreAllMocks()` | Restores every spy created with `vi.spyOn` |
To get this behavior in every test file without writing a hook, set restoreMocks: true in the test section of your config.
Common errors
- Spying on a missing method.
vi.spyOnthrows if the property doesn't exist or isn't a function. Check the spelling and make sure the object is the real instance or prototype. - Forgetting to restore. A spy on a shared object like
consoleorDateleaks into every later test in the file. - Expecting replacement by default. A bare spy still runs the real method, side effects included. Add
mockImplementationif the original does I/O. - Spying on module exports. ES module namespaces are read-only in some environments, such as Browser Mode. Use
vi.mockfor those, which the next chapter covers.
Exercise
A test runs const spy = vi.spyOn(Math, 'random').mockReturnValue(0.5) and never restores it. A later test in the same file checks that rollDie() returns different values across 100 calls, and it fails. Why, and what are two ways to fix it?
Show answer
The spy is still installed, so Math.random returns 0.5 on every call and rollDie always returns the same number. Fix it by calling spy.mockRestore() at the end of the first test, or by adding vi.restoreAllMocks() in an afterEach hook (or setting restoreMocks: true in the config).
Exercise
Given const service = { load() { return fetchData() } }, a module does const load = service.load at import time and later calls load(). Your test calls vi.spyOn(service, 'load') before running that code. Will the spy record the call?
Show answer
No. The module copied the original function into load before the spy replaced the property on service, so its calls never reach the spy. The code needs to call service.load() at call time, or the dependency should be mocked with vi.mock.