vi.spyOn in Vitest
From the Vitest cheat sheet · Mock Functions · verified Nov 2026
vi.spyOn
Spy on existing methods, getters, and setters, and restore them afterwards
typescript
const spy = vi.spyOn(cart, 'getTotal')
cart.getTotal()
expect(spy).toHaveBeenCalled()
vi.spyOn(cart, 'getTotal').mockReturnValue(0) // replace behavior
vi.spyOn(console, 'error').mockImplementation(() => {}) // silence logs
spy.mockRestore() // put the original back💡 spyOn keeps the real implementation until you mock it
📌 vi.restoreAllMocks only restores vi.spyOn spies, not vi.fn mocks
⚡ using spy = vi.spyOn(...) restores automatically at block end
⚠️ ESM namespace exports can't be spied on in Browser Mode
vi.spyOnspyrestore
Continue with Vitest
Save the full cheat sheet or work through every related task.