Mocks

Term side of the Card.
Topic: Testing
Unit title: Mocks
Categories: Concept
Explanation side of the Card

Explanation: The simulated objects used in testing to mimic the behavior of real objects, allowing testers to verify interactions and check if certain methods are called. They help isolate units and ensure that dependencies are correctly handled.

Example

Wrongts
const send = vi.fn();
await signUp('ann@example.com', { send });
expect(send).toHaveBeenCalled();
Rightts
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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy