Mocks
Example
const send = vi.fn();
await signUp('ann@example.com', { send });
expect(send).toHaveBeenCalled();const send = vi.fn();
await signUp('ann@example.com', { send });
expect(send).toHaveBeenCalledWith(
'ann@example.com',
expect.stringContaining('Welcome'),
);Checking the arguments proves the right email went to the right person, not just that some call happened.
Common mistakes
- Mocking so much that the test only checks the mocks, not the real code.
- Forgetting to restore a mock, so other tests fail in strange ways.
- Mocks that drift from the real API, so tests pass while production breaks.
Key points
- Mocks replace dependencies like email, payments or the network, never the module under test.
- Assertions check call arguments with
toHaveBeenCalledWith(), not only that a call happened. - Mocks are reset or restored between tests so state does not leak.
Interview questions
Mock vs stub: what is the difference?
A stub only returns preset data. A mock also records calls so the test can verify how it was used.
Is mocking bad practice?
No, but overuse is. Mock slow or external boundaries and test your own logic with real code.
How do I reset mocks between tests?
Call vi.restoreAllMocks() or jest.restoreAllMocks() in afterEach, or enable the restore option in the test config.