Jest 09 ๐ Mock Functions โ jest.fn() and Call Tracking
A Jest mock function is a function that records how it was called. jest.fn() creates it, the configuration methods set what it returns, and the call-tracking properties record every argument and result. The mock replaces a dependency in a test, and the assertions check the interactionโthe arguments passed, the number of calls, the return value usedโrather than only the output of the unit.
This chapter covers the jest.fn() API, the call-tracking properties and matchers, and the reset methods that keep a mock from leaking between tests. The sections that follow walk through creating and configuring a mock, inspecting its calls, and the clearMocks/resetMocks/restoreMocks configuration that automates the cleanup.
Key point: jest.fn() creates a mock that records its calls in mock.calls and its returns in mock.results; mockReturnValue/mockResolvedValue configure the behavior, toHaveBeenCalledWith/toHaveBeenCalledTimes assert on the interaction, and clearMocks/resetMocks/restoreMocks reset the mock between tests.
a. Creating and configuring a mock
jest.fn() returns a mock function. Without configuration, it returns undefined. The mockImplementation, mockReturnValue, and mockResolvedValue methods set the behavior, and the Once variants set it for a single call.
// A mock that returns undefined
const noop = jest.fn();
// With an implementation
const add = jest.fn((a, b) => a + b);
// Constant return
const getConfig = jest.fn().mockReturnValue({ debug: true });
// Resolved Promise
const fetchUser = jest.fn().mockResolvedValue({ id: "1", name: "Ana" });
// Rejected Promise
const fail = jest.fn().mockRejectedValue(new Error("nope"));
// Sequence: first, second, then "rest" for every call after
const sequence = jest.fn()
.mockReturnValueOnce("first")
.mockReturnValueOnce("second")
.mockReturnValue("rest");
The mockImplementation form is for a mock with logic; mockReturnValue is for a constant; mockResolvedValue is for an async function. The Once variants are for a mock that produces different results on successive calls, which is the pattern for a retry test or a paginated response.
The mock can also be created with the implementation in the call: jest.fn((a, b) => a + b). The two forms are equivalent.
The mockImplementationOnce and mockResolvedValueOnce variants are the per-call versions of the implementation methods, and they fall through to the next configured value when exhausted.
b. Inspecting the calls
The mock records every call in mock.calls, every return value in mock.results, and the this context in mock.contexts. The arrays are indexed by call order.
const log = jest.fn();
log("hello");
log("world", 42);
// Calls: [["hello"], ["world", 42]]
expect(log.mock.calls).toEqual([["hello"], ["world", 42]]);
// First call's first argument
expect(log.mock.calls[0][0]).toBe("hello");
// Number of calls
expect(log).toHaveBeenCalledTimes(2);
// Called with specific arguments (any call)
expect(log).toHaveBeenCalledWith("hello");
expect(log).toHaveBeenCalledWith("world", 42);
// Last call
expect(log).toHaveBeenLastCalledWith("world", 42);
// Nth call
expect(log).toHaveBeenNthCalledWith(1, "hello");
The toHaveBeenCalledWith matcher checks whether any call matched; toHaveBeenLastCalledWith checks the last call; toHaveBeenNthCalledWith checks a specific position. The toHaveBeenCalledTimes(n) matcher checks the count, and toHaveBeenCalled() is the shorthand for at least one call.
The mock.results array records the return value of each call, with a type of "return" or "throw" and the value. It is the way to assert on what the mock returned.
const fn = jest.fn().mockReturnValue(42);
fn();
expect(fn.mock.results[0]).toEqual({ type: "return", value: 42 });
The mock.lastCall property is the arguments of the last call, and mock.invocationCallOrder is the order in which the mock was called relative to other mocks. The invocation order is the mechanism for asserting that one mock was called before another.
c. Clearing, resetting, and restoring
The mock accumulates state across tests unless it is reset. The three reset methods have different scopes: mockClear() clears the call history but keeps the implementation; mockReset() clears the history and the implementation; mockRestore() restores the original function if the mock was created with jest.spyOn().
const fn = jest.fn().mockReturnValue(42);
fn();
fn.mockClear(); // history cleared, still returns 42
fn.mockReset(); // history and implementation cleared, returns undefined
The jest.clearAllMocks(), jest.resetAllMocks(), and jest.restoreAllMocks() functions apply the same operations to every mock in the test file. The config options clearMocks, resetMocks, and restoreMocks run the corresponding function before each test automatically.
// jest.config.js
module.exports = {
clearMocks: true,
restoreMocks: true,
};
The distinction that matters is clearMocks versus resetMocks. clearMocks keeps the implementation, so a mock that returns 42 still returns 42 in the next test. resetMocks removes the implementation, so the mock returns undefined until it is configured again.
The jest.spyOn() method creates a mock that wraps an existing method. The spy calls the original by default and records the call, and mockRestore() removes the spy and restores the original.
const obj = { greet: (name) => `Hello, ${name}` };
const spy = jest.spyOn(obj, "greet");
obj.greet("Ana");
expect(spy).toHaveBeenCalledWith("Ana");
spy.mockRestore(); // restores the original greet
The jest.spyOn() and jest.fn() distinction is the same as in Vitest: the spy is attached to a real object and calls the original by default, and the mock is standalone.
Complete Example Session
// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/user-service.js
async function createUser(api, data) {
return api.post("/users", data);
}
module.exports = { createUser };
// ============================================
// PART 2: THE MOCK
// ============================================
const { createUser } = require("./user-service");
describe("createUser", () => {
test("calls the API with the user data", async () => {
const api = {
post: jest.fn().mockResolvedValue({ id: "1", name: "Ana" }),
};
const result = await createUser(api, { name: "Ana" });
expect(api.post).toHaveBeenCalledTimes(1);
expect(api.post).toHaveBeenCalledWith("/users", { name: "Ana" });
expect(result).toEqual({ id: "1", name: "Ana" });
});
});
// ============================================
// PART 3: SEQUENCE
// ============================================
describe("sequence", () => {
test("returns different values per call", () => {
const fn = jest.fn()
.mockReturnValueOnce("first")
.mockReturnValueOnce("second");
expect(fn()).toBe("first");
expect(fn()).toBe("second");
expect(fn()).toBeUndefined();
});
});
// ============================================
// PART 4: THE RESET
// ============================================
describe("reset", () => {
test("clears the call history", () => {
const fn = jest.fn();
fn("a");
fn.mockClear();
expect(fn).not.toHaveBeenCalled();
});
});
The parts covered the mock with a resolved value, the sequence, and the reset.
Quick Reference
Mock Creation
| Call | Behavior |
|---|---|
jest.fn() | Returns undefined |
jest.fn((a) => a * 2) | With implementation |
.mockReturnValue(v) | Constant return |
.mockResolvedValue(v) | Resolved Promise |
.mockRejectedValue(e) | Rejected Promise |
.mockReturnValueOnce(v) | One call only |
Call Inspection
| Property/Matcher | Asserts |
|---|---|
mock.calls | Array of argument arrays |
mock.results | Array of return/throw records |
toHaveBeenCalled() | At least one call |
toHaveBeenCalledTimes(n) | Exact count |
toHaveBeenCalledWith(...) | Any call matches |
toHaveBeenLastCalledWith(...) | Last call matches |
toHaveBeenNthCalledWith(n, ...) | Nth call matches |
Reset Methods
| Method | Clears History | Clears Implementation |
|---|---|---|
mockClear() | Yes | No |
mockReset() | Yes | Yes |
mockRestore() | Yes | Restores original (spy) |
Best Practices
โ Do This:
// Configure the mock per test
const api = { post: jest.fn().mockResolvedValue(data) }; // โ
// Assert on the arguments
expect(api.post).toHaveBeenCalledWith("/users", { name: "Ana" }); // โ
// Restore spies
module.exports = { restoreMocks: true }; // โ
โ Don’t Do This:
// Share a configured mock across tests without reset
const mock = jest.fn().mockReturnValue(42); // module-level // โ
// Use resetMocks when the mock needs its implementation
module.exports = { resetMocks: true }; // every test reconfigures // โ
// Assert on the mock without configuring it
expect(mock()).toBe(42); // undefined unless configured // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
Mock returns undefined | resetMocks: true cleared the implementation | Configure per test or use clearMocks |
| Call history leaks | No reset between tests | clearMocks: true |
| Spy stays after test | No restore | restoreMocks: true |
toHaveBeenCalledWith passes on the wrong call | Matches any call | Use toHaveBeenLastCalledWith |
Real-World Examples
1. Basic mock
const fn = jest.fn();
2. Mock with implementation
const add = jest.fn((a, b) => a + b);
3. Resolved value
const fetchUser = jest.fn().mockResolvedValue({ id: "1" });
4. Sequence
jest.fn().mockReturnValueOnce(1).mockReturnValue(2);
5. Call count
expect(fn).toHaveBeenCalledTimes(2);
6. Called with
expect(fn).toHaveBeenCalledWith("a", 1);
7. Last call
expect(fn).toHaveBeenLastCalledWith("b");
8. Spy
const spy = jest.spyOn(obj, "method");
9. Restore
spy.mockRestore();
10. Config reset
module.exports = { clearMocks: true, restoreMocks: true };
Visual
The Mock’s Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ jest.fn() โ
โ โ โ
โ โผ โ
โ Configure: mockReturnValue / mockResolvedValue โ
โ โ โ
โ โผ โ
โ Call: records args in mock.calls โ
โ โ โ
โ โผ โ
โ Assert: toHaveBeenCalledWith / toHaveBeenCalledTimes โ
โ โ โ
โ โผ โ
โ Reset: mockClear / mockReset / restoreMocks โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Clear vs Reset
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ const fn = jest.fn().mockReturnValue(42); โ
โ fn(); โ
โ โ
โ mockClear() โ
โ calls: [] return: 42 โ
โ โ
โ mockReset() โ
โ calls: [] return: undefined โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Spy Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ jest.spyOn(obj, "method") โ
โ โ โ
โ โผ โ
โ Calls the original method by default โ
โ โ โ
โ โผ โ
โ Records the call โ
โ โ โ
โ โผ โ
โ mockRestore() โ original method restored โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Config Interaction
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ clearMocks: true โ
โ history cleared, implementation kept โ
โ โ
โ resetMocks: true โ
โ history and implementation cleared โ
โ โ every test must reconfigure its mocks โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Create | jest.fn() |
| Implementation | jest.fn((a) => a * 2) |
| Constant return | .mockReturnValue(v) |
| Async return | .mockResolvedValue(v) |
| Call history | mock.calls |
| Call matchers | toHaveBeenCalledWith, toHaveBeenCalledTimes |
| Clear | mockClear() |
| Reset | mockReset() |
| Spy | jest.spyOn(obj, "method") |
Key takeaways:
- A mock function records every call.
jest.fn()returns a function that tracks its arguments inmock.callsand its returns inmock.results, and thetoHaveBeenCalledWithmatchers assert on those records. - The behavior is configured per test.
mockReturnValue,mockResolvedValue, and theOncevariants set what the mock returns. A mock that is not configured returnsundefined. clearMockskeeps the implementation;resetMocksremoves it. A suite that configures its mocks inbeforeEachcan useresetMocks; a suite that configures them at module level needsclearMocks.jest.spyOn()wraps an existing method. The spy calls the original by default and records the call;mockRestore()removes the spy and restores the original.- The
toHaveBeenCalledWithmatcher passes if any call matches. UsetoHaveBeenLastCalledWithortoHaveBeenNthCalledWithwhen the specific call matters.
Remember: A mock is a function that remembers. It replaces the dependency, records the interaction, and lets the test assert on the boundary rather than the implementation. Configure the return, assert on the calls, and reset between tests. The three reset methods differ in what they clear, and the config option determines which one runs automatically. A mock that leaks its call history or its implementation produces a test that passes for the wrong reason.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!