vi.spyOn() for Method Mocking
You'll learn how to mock individual methods on objects while preserving the rest of the object's behavior and tracking how those methods are called.
What is vi.spyOn()?
While vi.mock() replaces entire modules, vi.spyOn() targets specific methods on existing objects. Think of it like wiretapping a phone line: the phone still works normally, but you're listening in and can optionally intercept calls.
This is invaluable when you need to:
- Mock a browser API (like
window.localStorage.setItem) - Replace a single method on a class instance
- Track how many times a method was called with which arguments
- Control what a method returns without mocking the entire object
How vi.spyOn() Works
import { vi, it, expect, beforeEach, afterEach } from 'vitest';
it('tracks localStorage calls', () => {
const spy = vi.spyOn(Storage.prototype, 'setItem');
// Component uses localStorage
render(<UserSettings />);
fireEvent.click(screen.getByRole('button', { name: /save/i }));
expect(spy).toHaveBeenCalledWith('theme', 'dark');
expect(spy).toHaveBeenCalledTimes(1);
spy.mockRestore(); // Restore original behavior
});
You can also control the return value:
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
// Now console.error does nothing during the test
Cleanup Pattern
Always restore spies to avoid test pollution:
let spy;
beforeEach(() => {
spy = vi.spyOn(window.navigator, 'onLine', 'get').mockReturnValue(false);
});
afterEach(() => {
spy.mockRestore();
});
Key Takeaway: vi.spyOn() lets you mock individual methods while tracking their usage and preserving the rest of the object's functionality—perfect for browser APIs and selective mocking.