Concept Explanation
A good unit test checks one thing in isolation. But real functions have messy dependencies — they call an API, read the clock, or hit a database. You don't want your "calculate total" test to fail because the payment server is down.
Mocks and spies are stunt doubles. A spy wraps a function and records how it was called (how many times, with what arguments). A mock goes further — it replaces the real thing with a fake that returns whatever you want, so the test stays fast and predictable.
Syntax or Core Structure
import { vi, expect, test } from "vitest";
test("spy records calls", () => {
const spy = vi.fn(); // a blank mock function
spy("hello");
expect(spy).toHaveBeenCalledWith("hello");
expect(spy).toHaveBeenCalledTimes(1);
});
Replace a real module with a fake:
vi.mock("./api", () => ({
fetchUser: vi.fn(() => Promise.resolve({ name: "Test" }))
}));
Real World Example
Faking Time: Testing a "session expires after 30 minutes" feature would take 30 real minutes. With vi.useFakeTimers() you fast-forward the clock instantly and assert the session expired.
Common Mistakes
- Over-Mocking: If you mock everything, you're testing your mocks, not your code. Mock only true external boundaries.
- Forgetting to Reset: A mock's call history leaks into the next test. Call
vi.clearAllMocks()inbeforeEach. - Mocking What You Own: Prefer refactoring so pure logic needs no mocks at all.
Best Practices
- Mock at the Edge: Fake the network and the clock, not your own business logic.
- Assert the Contract: Check that the API was called correctly, not the internal steps.
- Restore Timers: Always
vi.useRealTimers()after a fake-timer test.
Practice Exercises
- The Spy: Create a
vi.fn(), call it twice, and assert it was called two times. - The Fake API: Mock a
fetchUserfunction to return a fixed user and test code that uses it. - The Time Traveler: Use fake timers to test a function that runs after
setTimeout(fn, 5000).