Jest · Unit tests that survive refactors
How do mock functions work in Jest?
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.
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",
});Configuring a mock
mockReturnValue(value)for a fixed returnmockReturnValueOnce(value)for a sequence of returnsmockImplementation(fn)when behaviour depends on the argumentsmockResolvedValueandmockRejectedValuefor async dependenciesmockImplementationOncefor 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.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between mockClear, mockReset and mockRestore?
- 2How do you make a mock return different values on successive calls?
- 3When does mocking a dependency make a test less valuable?
- 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.