| | |

Jest 09 ๐Ÿƒ Mock Functions โ€” jest.fn() and Call Tracking

โฑ๏ธ Estimated read: 8 min | |

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

CallBehavior
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/MatcherAsserts
mock.callsArray of argument arrays
mock.resultsArray 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

MethodClears HistoryClears Implementation
mockClear()YesNo
mockReset()YesYes
mockRestore()YesRestores 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

PitfallWhy It HappensFix
Mock returns undefinedresetMocks: true cleared the implementationConfigure per test or use clearMocks
Call history leaksNo reset between testsclearMocks: true
Spy stays after testNo restorerestoreMocks: true
toHaveBeenCalledWith passes on the wrong callMatches any callUse 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

ItemValue
Createjest.fn()
Implementationjest.fn((a) => a * 2)
Constant return.mockReturnValue(v)
Async return.mockResolvedValue(v)
Call historymock.calls
Call matcherstoHaveBeenCalledWith, toHaveBeenCalledTimes
ClearmockClear()
ResetmockReset()
Spyjest.spyOn(obj, "method")

Key takeaways:

  • A mock function records every call. jest.fn() returns a function that tracks its arguments in mock.calls and its returns in mock.results, and the toHaveBeenCalledWith matchers assert on those records.
  • The behavior is configured per test. mockReturnValue, mockResolvedValue, and the Once variants set what the mock returns. A mock that is not configured returns undefined.
  • clearMocks keeps the implementation; resetMocks removes it. A suite that configures its mocks in beforeEach can use resetMocks; a suite that configures them at module level needs clearMocks.
  • 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 toHaveBeenCalledWith matcher passes if any call matches. Use toHaveBeenLastCalledWith or toHaveBeenNthCalledWith when 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.

Was this helpful?


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!