Jest · Unit tests that survive refactors

How do mock functions work in Jest?

Easymock functionsjest.fnspiesUpdated Oct 2026
Quiz this track

Short answer

jest.fn() creates a stand-in that records calls and returns undefined by default. Configure return values or implementations, then assert on calls with toHaveBeenCalledWith and related matchers.

A mock function replaces a dependency so a unit can be tested without its real collaborators. It records every call, the arguments and the returned value. That record is what lets you assert that a component called the API once with the right payload.

ts
const sendEmail = jest.fn().mockResolvedValue({ ok: true });

await notifyUser("asha@example.com", { sendEmail });

expect(sendEmail).toHaveBeenCalledTimes(1);
expect(sendEmail).toHaveBeenCalledWith("asha@example.com", {
  subject: "Welcome",
});
The mock stands in for a slow or external dependency while the unit logic runs for real.

Configuring a mock

  • mockReturnValue(value) for a fixed return
  • mockReturnValueOnce(value) for a sequence of returns
  • mockImplementation(fn) when behaviour depends on the arguments
  • mockResolvedValue and mockRejectedValue for async dependencies
  • mockImplementationOnce for a different result on one call

Clearing, resetting and restoring are different operations. mockClear removes call history, mockReset removes history and implementation, and mockRestore returns the original implementation for a spy. Pick deliberately, because a reset in the wrong place can silently change what a later test receives.

Over-mocking is a smell. If every collaborator is mocked, the test verifies wiring rather than behaviour. Mock only the boundary that is slow, non-deterministic or outside the unit.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between mockClear, mockReset and mockRestore?
  2. 2How do you make a mock return different values on successive calls?
  3. 3When does mocking a dependency make a test less valuable?
  4. 4How do you assert on the arguments of the second call?

Say it in the interview

jest.fn creates a callable stand-in that records its calls. I give it a return value or implementation, then assert with toHaveBeenCalledWith or inspect mock.calls. For async dependencies I use mockResolvedValue and mockRejectedValue. I keep mocks at system boundaries, because mocking every collaborator produces tests that prove the wiring rather than the behaviour.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.