Mocks
A mock is a stand-in for a dependency you do not want to run for real. It records calls and can return canned values so the test stays fast and deterministic.
Detailed Explanation
Tests should fail when your code is wrong, not when the network is down. A mock replaces fetch, a database, or a clock. The words blur: a stub returns data; a spy wraps a real function and records calls; a mock is often a spy plus assertions on how it was called. In Jest/Vitest, jest.fn() / vi.fn() covers all three.
fn.mockReturnValue(1) and mockResolvedValue(user) set results. mockImplementation((id) => ...) runs logic. toHaveBeenCalledWith("ada") asserts the contract between your code and the dependency.
Module mocks (vi.mock("./db.js")) replace the whole module for the test file. Use them when the unit imports a singleton. Prefer injecting the dependency (createService({ fetch })) so tests pass a fake without a module graph hack.
Good mocks are narrow. Mock fetch at the boundary, not JSON.parse. Over-mocking (every class in the system is a mock) tests the mocks. Under-mocking (real HTTP in a unit test) is slow and flaky.
What it costs you: tests that pass while production is broken, because the mock's shape drifted. Refresh mocks when the API changes. mockReset vs mockRestore vs mockClear differ; restore spies that replaced real methods so later tests see the original.
Reach for a mock when the real thing is slow, nondeterministic, or has side effects. Reach for the real thing in an integration test against a local container. Reach for a spy when you want the real implementation plus a call count.
Time and randomness are dependencies. A mock clock and a seeded Math.random turn a flake into a unit test. Do not mock Date in a file that also tests formatting across time zones unless you control the zone. Prefer injecting now = () => Date.now() so the mock stays local.
When a mock must simulate a sequence (mockResolvedValueOnce three times), assert the call count. A fourth call returning undefined is a test bug that looks like a product bug.
Code Examples
async function loadEmail(id, fetchImpl) {
const res = await fetchImpl(`/users/${id}`);
const body = await res.json();
return body.email;
}
const fetchImpl = vi.fn().mockResolvedValue({
json: async () => ({ email: "ada@example.com" }),
});
await expect(loadEmail(7, fetchImpl)).resolves.toBe("ada@example.com");
expect(fetchImpl).toHaveBeenCalledWith("/users/7");const now = vi.spyOn(Date, "now").mockReturnValue(1_700_000_000_000);
expect(Date.now()).toBe(1_700_000_000_000);
now.mockRestore();Common Gotchas
`mockResolvedValue` is for the promise result
`mockReturnValue(Promise.resolve(x))` also works; mixing them with sync code is confusing.
Module mocks leak if you forget `vi.clearAllMocks` / `restoreAllMocks`
isolate in `afterEach`.
A mock that returns `undefined` by default
forgotten `mockReturnValue` is a real class of bugs in the *test*.
Prefer injection over `vi.mock` when you control the constructor
easier to read, no hoist surprises.