Skip to the page

Test runners, assertions and mocks · mid

Mocks, spies and module mocking

A mock function records how it was called and returns what you tell it to, a spy wraps a real method, and module mocking replaces an import; mock at the boundaries you do not control (network, time, randomness, native modules) and avoid mocking the code you are testing.

The notes

What you must know

  • jest.fn() / vi.fn(): records calls (mock.calls) and results; set behaviour with mockReturnValue, mockReturnValueOnce, mockResolvedValue, mockImplementation.
  • jest.spyOn(obj, 'method') / vi.spyOn: wraps a real method so you can watch it or change it; restore it afterwards (mockRestore, or using spies in Jest 30).
  • Module mocks: jest.mock('./api') / vi.mock('./api') are hoisted to the top of the file, so the mock is in place before imports run. Use the factory's real module (requireActual / importOriginal) for partial mocks.
  • clear (forget calls) vs reset (also remove implementations) vs restore (put back the original for spies). Vitest 5 clears mocks before each test by default.
  • Mock boundaries: network (prefer MSW over mocking fetch or axios), timers, Date, Math.random, analytics SDKs, React Native native modules. Don't mock child components or the hook you are testing.
  • Over-mocking makes tests pass while the real integration is broken; each mock is an assumption that can drift from reality.

The red pen

Common traps: mistake → fix

  • Mistake: "Mock everything to make it a pure unit test"

    Fix: you end up testing your mocks; mock only real boundaries.

  • Mistake: "jest.mock inside a test only affects that test"

    Fix: module mocks are hoisted and apply to the whole file.

  • Mistake: "Spies restore themselves"

    Fix: without restore (or using) a spy leaks into later tests.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between a mock, a stub and a spy?
  2. How does jest.mock / vi.mock work, and why is it hoisted?
  3. When is mocking a bad idea?
  4. How would you test a component that calls an analytics SDK and the API?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview