Spies
Observe real function calls without replacing them using vi.spyOn and jest.spyOn.
What you'll learn
- What a spy is and how it differs from a stub or mock
- Wrapping real methods with spyOn to observe calls
- Asserting call count, arguments, and return values on spies
- Restoring spies to avoid leaking into other tests
Concept
Spies Observe
A spy wraps an existing function or method and records how it was called — arguments, return value, call count — while by default still delegating to the real implementation. This lets you verify that your code called a collaborator correctly without replacing the collaborator's behavior. Spies are ideal when the real function is safe to run but you need to confirm the interaction.
spyOn
In Vitest use vi.spyOn(object, "method"), in Jest jest.spyOn(object, "method"). The spy replaces object.method with a wrapper that records calls and forwards to the original. You can then assert with toHaveBeenCalledTimes, toHaveBeenCalledWith, and toHaveReturnedWith. If you need to change the behavior, chain .mockImplementation or .mockReturnValue on the spy.
Spies vs Mocks vs Stubs
A spy wraps real behavior and observes; a stub replaces behavior to feed answers; a mock replaces behavior and asserts expectations. Use a spy when the real function is cheap and deterministic and you mainly want to confirm it was called. Use a stub when you must change what the function returns. Use a mock when the interaction contract is the point of the test.
Cleanup
Spies mutate the object they wrap, so they leak across tests if not restored. Use vi.restoreAllMocks() or spy.mockRestore() in an afterEach to put the original method back. Without cleanup, a spy on Date.now in one test can silently affect every later test in the file, producing mysterious order-dependent failures.
In Practice
Spies are most valuable when you want to confirm a side effect happened without changing the behavior that produces it — for example, verifying that a service logged a warning while still letting the real logger print. When you also need to change what the spied method returns, chain .mockImplementation or .mockReturnValue onto the spy; this turns it into a hybrid that both observes and overrides. Be careful spying on methods of shared singletons or globals like console or Date, because the mutation outlives the test unless you restore it. If you find yourself spying on many methods of one object, consider whether a stub or fake would express the intent more clearly. A spy answers "did my code call this, and how?" — reach for it when that question is the point of the test.
Example
import { describe, it, expect, vi, afterEach } from "vitest";
const logger = {
warn(message: string) {
console.warn(message); // real implementation
},
};
describe("cart with spy on logger", () => {
afterEach(() => vi.restoreAllMocks());
it("logs a warning when removing a missing item", () => {
const spy = vi.spyOn(logger, "warn");
const cart = new Cart(logger);
cart.remove(999); // item does not exist
expect(spy).toHaveBeenCalledWith(expect.stringContaining("not found"));
});
});
The spy wraps the real logger.warn so the warning still prints, but the test can also assert it was called with the right message. afterEach restores the original.
Try it
- Code Diff
Compare recorded spy call arguments to expected ones.
- JSON Formatter
Inspect the structured arguments spies capture.
Common mistakes
The mistake
Forgetting to restore spies
The fix
Always add afterEach(() => vi.restoreAllMocks()) (or jest.restoreAllMocks) when using spyOn, or the wrapped method leaks into later tests.
The mistake
Spying on a method that does not exist on the object
The fix
spyOn requires the property to already exist. If you need to add a new method, use vi.fn() and assign it, or vi.stubEnv for globals.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.