Spies and Stubs
A stub replaces a function's result. A spy records how a function was called, optionally wrapping the real one. Mocks in Jest and Vitest are spies you can stub.
Detailed Explanation
The test-double vocabulary is older than Jest. A dummy is a unused argument. A stub answers with canned data (() => 42). A spy sits on a real method and counts calls (jest.spyOn(console, "error")). A fake is a working lightweight implementation (an in-memory store). A mock (in the classical sense) is a spy you assert on.
In practice you write const fn = vi.fn() (a spy/stub with no original) or vi.spyOn(obj, "method") (wraps the original). spy.mockImplementation(...) turns the spy into a stub. spy.mockRestore() puts the original method back.
When to spy on the original: you want side effects to happen (a real formatter) but you also want to assert it ran. When to stub: the original would hit the network or the clock. When to fake: the real algorithm is the thing under test's partner (a repository) and a 20-line Map is clearer than a mock with twelve mockResolvedValueOnce.
Spies on modules (spyOn(service, "save")) require the method to be a property lookup. Destructuring (const { save } = service) at import time copies the function and the spy never runs. Spy before the call, and do not copy the function in the unit if you need to intercept it — or inject it.
What it costs you: spies that outlive the test and change global behaviour (Date.now, console.log). Always restore. Stubs that ignore arguments hide the fact that production passed the wrong id.
Reach for a stub when you only need a return value. Reach for a spy when the assertion is "this collaborator was called". Reach for a fake when the collaborator's behaviour matters and is small.
Code Examples
const math = {
double(n) {
return n * 2;
},
};
const spy = vi.spyOn(math, "double");
expect(math.double(3)).toBe(6);
expect(spy).toHaveBeenCalledWith(3);
spy.mockRestore();const stub = vi.fn().mockReturnValue("ok");
expect(stub("ignored")).toBe("ok");
expect(stub).toHaveBeenCalledTimes(1);const fakeRepo = {
rows: new Map([[7, { id: 7 }]]),
async find(id) {
return this.rows.get(id) ?? null;
},
};
await expect(fakeRepo.find(7)).resolves.toEqual({ id: 7 });Common Gotchas
Spying after destructure misses the call
`const { save } = api; vi.spyOn(api, "save")` does not wrap the copied `save`.
Restore spies on globals in `afterEach`
a leaked `Date.now` mock breaks later files in the same worker.
`mockClear` clears history; `mockReset` also clears impl; `mockRestore` restores the original
pick the one you mean.
`toHaveBeenCalled` is a mock assertion
a stub you never assert on is just a return value, which is fine.