Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 30 ยท Mocking

Mock Functions with jest.fn

Learn Jest mock functions: jest.fn, mock.calls and mock.results, mockReturnValue, mockImplementation, toHaveBeenCalledWith, plus a runnable stand-in built on node:test.

Most code does not live alone. A function sends an email, calls an API, writes to a log, or hands a result to a callback. When you test such a function, you rarely want the real email to go out. What you want to know is smaller and sharper: was the helper called, how many times, and with which arguments?

A mock function answers those questions. It is a stand-in function that records every call made to it, and that you can program to return whatever the test needs. In Jest you create one with jest.fn(). This lesson covers what a mock records, how to program its behavior, and the matchers that check it. If you have not met matchers yet, read Common Matchers first.

The real Jest needs Node.js and the jest package, so the Jest code below is read-only. The runnable examples use plain Node.js: one builds a tiny fn() that behaves like jest.fn() so you can see the bookkeeping, and one uses the mock functions that ship with Node's own node:test module. Both are stand-ins, and each one says so.

What a mock function gives you

It records Every call, its arguments and its result.
It is programmable Return a value, resolve a promise or throw.
It replaces a dependency No real network, email or database.

You test your code's behavior, not the helper's.

1 / 2

Creating and calling a mock

A bare jest.fn() does nothing and returns undefined, but it remembers everything:

JavaScript
test("a callback receives each item", () => {
  const onItem = jest.fn();

  [10, 20, 30].forEach(onItem);

  expect(onItem).toHaveBeenCalledTimes(3);
  expect(onItem).toHaveBeenCalledWith(10, 0, [10, 20, 30]);
});

forEach passes three arguments (the item, its index and the array), so that is what the mock recorded. This is a classic use: pass a mock as a callback and assert how your code used it.

The onItem variable is a real function, so you can hand it to anything that expects a function. The extra data lives in a property called onItem.mock.

What a mock records

The .mock property holds the history. These are the fields you will use most:

Property Contents
mock.calls An array with one entry per call; each entry is the array of arguments.
mock.results One entry per call: { type: "return", value }, { type: "throw", value } or { type: "incomplete" } while the call is still running.
mock.lastCall The arguments of the most recent call, or undefined.
mock.contexts The value of this for each call.
mock.instances The objects created when the mock was called with new.
mock.invocationCallOrder A global counter, so you can compare the order of calls across different mocks.
JavaScript
const add = jest.fn((a, b) => a + b);

add(2, 3);
add(10, 5);

console.log(add.mock.calls);        // [[2, 3], [10, 5]]
console.log(add.mock.results[1]);   // { type: "return", value: 15 }
console.log(add.mock.lastCall);     // [10, 5]

Reading mock.calls directly is handy for complex arguments, but the matchers below usually read better and give clearer failure messages.

Programming return values

A mock is more useful when it can play a role. Jest gives you several ways to say what it should do:

JavaScript
const getPrice = jest.fn();

getPrice.mockReturnValue(9.99);        // every call returns 9.99
getPrice.mockReturnValueOnce(5);       // the next call returns 5, then back to 9.99

const load = jest.fn();
load.mockResolvedValue({ id: 1 });     // returns Promise.resolve(...)
load.mockRejectedValue(new Error("offline")); // returns Promise.reject(...)

mockReturnValueOnce calls queue up, one per call, which makes it easy to script a sequence: a first call that succeeds and a second one that returns something else. When the queue is empty, the mock falls back to its default behavior.

For anything dynamic, supply a function with mockImplementation, or pass it straight to jest.fn:

JavaScript
const double = jest.fn((n) => n * 2);                 // same as below
const triple = jest.fn().mockImplementation((n) => n * 3);

const flaky = jest.fn()
  .mockImplementationOnce(() => { throw new Error("first call fails"); })
  .mockImplementation(() => "ok");

Chaining reads like a script: the first call throws, every call after that returns "ok". This pattern is perfect for testing retry logic. See Testing Promises and Async/Await for how to assert on the promise-returning variants.

Give a mock a name with .mockName("sendEmail"). Failure messages then say sendEmail instead of jest.fn(), which saves time when a test uses several mocks.

Matchers for mock functions

You assert on mocks with a family of matchers:

JavaScript
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenCalledWith("alice", { admin: true });
expect(fn).toHaveBeenLastCalledWith("bob");
expect(fn).toHaveBeenNthCalledWith(1, "alice");   // 1-based call number
expect(fn).toHaveReturnedWith(42);
expect(fn).toHaveLastReturnedWith(42);
expect(fn).not.toHaveBeenCalled();

The argument check in toHaveBeenCalledWith uses the same recursive equality as toEqual, so objects are compared by content, not by identity. You can use asymmetric matchers inside it, which is useful when part of the argument is unpredictable:

JavaScript
expect(save).toHaveBeenCalledWith({
  name: "Ada",
  createdAt: expect.any(Date),
});

Older code may use the aliases toBeCalled, toBeCalledWith and lastCalledWith. Recent Jest versions removed them, so use the toHaveBeen... names shown here.

A realistic example

Say you have a function that sends a welcome message and reports errors through a logger it receives as a parameter:

JavaScript
async function welcome(user, sendEmail, log) {
  try {
    await sendEmail(user.email, `Welcome, ${user.name}!`);
    return true;
  } catch (error) {
    log(`email failed for ${user.email}: ${error.message}`);
    return false;
  }
}

A Jest test replaces both helpers with mocks, so nothing real is sent:

JavaScript
test("welcome sends one email", async () => {
  const sendEmail = jest.fn().mockResolvedValue(undefined);
  const log = jest.fn();

  const ok = await welcome({ name: "Ada", email: "[email protected]" }, sendEmail, log);

  expect(ok).toBe(true);
  expect(sendEmail).toHaveBeenCalledTimes(1);
  expect(sendEmail).toHaveBeenCalledWith("[email protected]", "Welcome, Ada!");
  expect(log).not.toHaveBeenCalled();
});

test("welcome logs a failure and returns false", async () => {
  const sendEmail = jest.fn().mockRejectedValue(new Error("smtp down"));
  const log = jest.fn();

  const ok = await welcome({ name: "Ada", email: "[email protected]" }, sendEmail, log);

  expect(ok).toBe(false);
  expect(log).toHaveBeenCalledWith("email failed for [email protected]: smtp down");
});

Notice that the test never sends mail. It checks the contract between welcome and its collaborators. This style of passing dependencies in as parameters is called dependency injection, and it makes mocking trivial. Mocking Modules shows what to do when you cannot change the function signature.

Stand-in 1: build jest.fn yourself

There is no magic in a mock function. It is a function that pushes its arguments to an array, calls an implementation and stores the outcome. The stand-in below is a small version of jest.fn() with calls, results, mockReturnValue, mockImplementation and the one-shot queue. It is NOT Jest's code (real Jest also tracks contexts, instances and call order across mocks), but it makes the bookkeeping visible.

Node.js A tiny jest.fn() stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The once queue is why a scripted sequence works: each call takes the next queued implementation, and only when the queue is empty does the default apply. The try/catch is how a real mock can record type: "throw" and still let the error reach your code.

Stand-in 2: node:test mock functions

Node.js ships its own mock functions in node:test. The idea is the same, but the API is spelled differently: mock.fn() creates the function, and the history lives in fn.mock.calls, where each entry is an object with arguments, result, error and this. This is real Node code, but it is Node's API, not Jest's, so use it to confirm the concepts rather than as a copy-paste source.

Node.js node:test mock functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The shape of the checks is identical to the Jest version above: call the function under test with mocks, then ask the mocks what happened. Only the spelling of the questions changes.

Common mistakes

  • Forgetting to clear between tests. A mock created at the top of a file keeps its calls across tests. Create mocks inside each test, or clear them in beforeEach, or set clearMocks: true in the config. See Spying with jest.spyOn for the difference between clearing, resetting and restoring.
  • Asserting too much. Checking every call of every helper makes tests break when you refactor. Assert on the calls that are part of the behavior you promised.
  • Mocking what you own and can run cheaply. A pure function is usually better called for real. Mock the slow, random or external parts.
  • Surprise arguments. toHaveBeenCalledWith compares the whole argument list, so extra arguments you did not expect (like the index and array that forEach passes) make the match fail.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a bare jest.fn() return when you call it?

    Without an implementation or a configured return value, a mock function returns undefined, but it still records the call.
  2. 2. Which property holds the arguments of every call as an array of arrays?

    fn.mock.calls has one entry per call and each entry is the list of arguments. mock.results holds what each call returned or threw.
  3. 3. You want a mock to throw on its first call and return "ok" on all later calls. What do you use?

    The one-shot implementation is used for the first call, and the regular implementation takes over afterwards.
  4. 4. Which matcher checks the second call of a mock?

    toHaveBeenNthCalledWith counts calls starting at 1, so the first argument 2 selects the second call.

Summary

  • jest.fn() creates a function that records its calls in .mock.calls, its outcomes in .mock.results and its this values in .mock.contexts.
  • Program behavior with mockReturnValue, mockResolvedValue, mockRejectedValue and mockImplementation; the ...Once variants queue one-shot behavior.
  • Assert with toHaveBeenCalledTimes, toHaveBeenCalledWith, toHaveBeenNthCalledWith and toHaveReturnedWith.
  • Passing collaborators as parameters makes functions easy to test with mocks.
  • A mock is just a function plus an array of records, as the stand-in showed.

Next, learn to watch and replace methods on existing objects in Spying with jest.spyOn.