skip to content

Mocks and Spies

jest.fn and jest.spyOn, module mocking with jest.mock, manual mocks, and the difference between mockClear, mockReset, and mockRestore. Interviewers ask because leftover mock state between tests is a classic source of order-dependent failures.

on this pageshow

explore

questions

6

In Jest 30, what does a jest.fn() mock function record about its calls, and which matchers read that record back?

level: juniorimportance: must knowfreq 76%

answer

  1. a record kept on the function
  2. one property holds the history
  3. arguments, outcomes, this values, instances
  4. toHave... primary matcher names

basics

~20 s

A jest.fn() mock records every call on its mock property: arguments in mock.calls, outcomes in mock.results, plus this values and instances. Matchers such as toHaveBeenCalledTimes and toHaveBeenCalledWith read that record; Jest 30 removed aliases like toBeCalled.

solid answer

~30 s

`jest.fn()` returns a callable function that writes every call into its `mock` property: `mock.calls` holds one argument array per call, `mock.results` holds `{type, value}` per call (`'return'`, `'throw'` or `'incomplete'`), and `mock.contexts`, `mock.instances` and `mock.lastCall` cover `this`, `new` and the latest call. With no implementation it returns `undefined`. I read the record through matchers: `toHaveBeenCalled`, `toHaveBeenCalledTimes(n)`, `toHaveBeenCalledWith(...)`, `toHaveBeenLastCalledWith`, `toHaveBeenNthCalledWith(n, ...)` and the `toHaveReturned` family. Arguments compare with `toEqual`'s recursive equality, and `toHaveBeenCalledWith` passes if any call matches, so I pair it with a count. In Jest 30 only these `toHave...` names exist; the aliases such as `toBeCalled` and `lastCalledWith` were removed.

code

javascript · 18 lines
javascript
function settleOrder(order, charge, logger) {
  const receipt = charge(order.id, order.totalCents);
  logger.info(`charged ${order.id}`);
  return receipt.id;
}

test('settleOrder charges the total once and logs it', () => {
  const charge = jest.fn().mockReturnValue({ id: 'rcpt_1' });
  const logger = { info: jest.fn() };

  expect(settleOrder({ id: 'ord_1', totalCents: 4200 }, charge, logger)).toBe('rcpt_1');

  expect(charge).toHaveBeenCalledTimes(1);
  expect(charge).toHaveBeenCalledWith('ord_1', 4200);
  expect(charge.mock.calls[0]).toEqual(['ord_1', 4200]);
  expect(charge.mock.results[0]).toEqual({ type: 'return', value: { id: 'rcpt_1' } });
  expect(logger.info).toHaveBeenLastCalledWith('charged ord_1');
});

go deeper

for a junior

Know that jest.fn() records calls on its mock property and name the main matchers: toHaveBeenCalled, toHaveBeenCalledTimes and toHaveBeenCalledWith, in their Jest 30 spelling.

for a middle

Explain mock.calls versus mock.results, the 'return', 'throw' and 'incomplete' result types, and why toHaveBeenCalledWith uses toEqual-style equality and passes on any matching call.

for a senior

Show how a weak call assertion hides a bug, such as an extra wrong call or a count inflated by an earlier test, and how pairing a count with an argument check closes it.

for a principal

Weigh how much a suite should lean on call assertions at all, and how a Jest 30 upgrade's alias removal is best rolled out across many packages in one sweep.

## What `jest.fn()` gives you `jest.fn()` returns a **mock function**: a real, callable function that Jest has wrapped so that every call is written down. With no argument it does nothing and returns `undefined`. With an implementation, `jest.fn(impl)`, it runs that implementation and still records the call. In an order service that receives a payment `charge` function and a `logger` object, a test passes `jest.fn()` mocks in their place, runs the code, and then asks the mocks what happened to them. ## The `mock` property: the call record Every mock function carries a `mock` property, and the whole record lives there: - **`mock.calls`**: an array with one entry per call, each entry being the array of arguments for that call. After `charge('ord_1', 4200)` and `charge('ord_2', 999)` it holds `[['ord_1', 4200], ['ord_2', 999]]`. - **`mock.results`**: one entry per call, each an object with a `type` and a `value`. The `type` is `'return'` when the call returned normally, `'throw'` when it threw, and `'incomplete'` while the call has not finished yet, which you only observe when inspecting from inside the mock itself. - **`mock.instances`**: the objects created when the mock was called with `new`. - **`mock.contexts`**: the `this` value of each call, as set by `bind`, `call` or `apply`. - **`mock.lastCall`**: the argument array of the most recent call, or `undefined` if the mock was never called. One subtlety hides in `mock.results`. An async mock returns a promise, so its entry is `'return'` with the promise as `value`, even if that promise later rejects: the call itself did not throw. A test that cares about the rejection awaits the promise rather than reading `type`. You can also label a mock with `mockName('charge')`. The name replaces the default `jest.fn()` label in failure output, which helps when one test holds several mocks. ## Matchers that read the record Reading `mock.calls` by hand works, but the dedicated matchers print the expected and received calls side by side when they fail, which makes a broken test far quicker to diagnose. | Matcher | Passes when | |---|---| | `toHaveBeenCalled()` | the mock was called at least once | | `toHaveBeenCalledTimes(n)` | the mock was called exactly `n` times | | `toHaveBeenCalledWith(...args)` | at least one recorded call had these arguments | | `toHaveBeenLastCalledWith(...args)` | the most recent call had these arguments | | `toHaveBeenNthCalledWith(n, ...args)` | call number `n`, counting from 1, had these arguments | | `toHaveReturned()` / `toHaveReturnedWith(value)` | at least one call returned without throwing, or returned that value | Arguments are compared with the same recursive equality that `toEqual` uses, so a fresh literal `{ id: 1 }` matches a different object with the same fields. Asymmetric matchers such as `expect.any(Number)` work in any argument slot. The matchers also validate how they are used: 1. Handing them a plain function that is not a mock or spy fails with "received value must be a mock or spy function". 2. Writing `toHaveBeenCalled(2)` fails with "this matcher must not have an expected argument"; the count belongs in `toHaveBeenCalledTimes(2)`. 3. `toHaveBeenNthCalledWith(0, ...)` fails because `n` must be a positive integer; the first call is number `1`. ## The Jest 30 names Jest 30 removed the alias matchers that had been deprecated since Jest 26. `toBeCalled`, `toBeCalledTimes`, `toBeCalledWith`, `lastCalledWith`, `nthCalledWith`, `toReturn`, `toReturnTimes`, `toReturnWith`, `lastReturnedWith` and `nthReturnedWith` are gone, and each has a `toHave...` primary name with identical behaviour. A suite upgraded from Jest 29 that still uses one fails with a `TypeError` such as `expect(...).toBeCalled is not a function`. A search-and-replace to the primary names is the whole fix; the matching logic did not change. ## Habits that keep call assertions honest - **Pair a count with an argument check.** `toHaveBeenCalledTimes(1)` plus `toHaveBeenCalledWith(...)` proves "once, with these arguments", whereas `toHaveBeenCalledWith` alone still passes when an extra, wrong call also happened. - **Remember that the record accumulates.** A mock created at file scope keeps the calls of earlier tests until something clears it, so a count can be off by the calls a previous test made. - **Assert the whole history when order matters.** `expect(charge.mock.calls).toEqual([['ord_1', 4200]])` states every call and its order in one line. - **Prefer the matcher over raw indexing.** `charge.mock.calls[0][1]` throws an unhelpful `TypeError` when the mock was never called, while the matcher reports the received call count plainly.

  • Why can toHaveBeenCalledWith pass even though the mock was also called with the wrong arguments?
    `toHaveBeenCalledWith` passes when any recorded call matches, so an extra wrong call does not fail it. To prove there was exactly one call and that it was right, add `toHaveBeenCalledTimes(1)`, use `toHaveBeenLastCalledWith` or `toHaveBeenNthCalledWith` for a specific position, or assert the full `mock.calls` array with `toEqual`.
  • How do you assert on what a mock returned rather than on what it received?
    Use `toHaveReturned`, `toHaveReturnedTimes`, `toHaveReturnedWith`, `toHaveLastReturnedWith` or `toHaveNthReturnedWith`, or read `mock.results`. For a mock that returns a promise, the recorded value is the promise itself, so await the call in the test to check what it resolved or rejected with.
  • What happens when a Jest 29 suite using toBeCalledWith is run on Jest 30?
    Each such assertion throws a `TypeError`, because the alias no longer exists on the `expect` object, so the test fails before checking anything. Renaming to `toHaveBeenCalledWith` restores it with identical behaviour; the same goes for `lastCalledWith`, `nthCalledWith` and the `toReturn...` aliases.

  • toBeCalledWith still works in Jest 30; it only prints a deprecation warning.
  • toHaveBeenCalledWith compares arguments by reference, the way toBe does.
  • toHaveBeenCalledWith checks only the most recent call.
  • A mock that returned a promise which later rejected is recorded as type 'throw'.
  • A jest.fn() with no implementation throws when it is called.
  • mock.calls starts empty again at every test without any configuration.

Assumes Jest 30, which removed the deprecated alias matchers such as toBeCalled, toBeCalledWith and lastCalledWith that Jest 29 still accepted.

open as a page

In Jest 30, what separates mockClear, mockReset and mockRestore, and which config keys run their all-mocks forms before every test?

level: middleimportance: must knowfreq 72%

basics

~10 s

mockClear empties the call record; mockReset also removes implementations, so the mock returns undefined; mockRestore also puts a jest.spyOn original back. clearMocks, resetMocks and restoreMocks run clearAllMocks, resetAllMocks and restoreAllMocks before each test.

open as a page

In Jest 30, how does jest.spyOn(object, methodName) differ from assigning jest.fn() to that method, and how is the original put back?

level: middleimportance: must knowfreq 66%

basics

~20 s

jest.spyOn swaps object[methodName] for a mock that records calls and, by default, still runs the original; mockRestore or jest.restoreAllMocks puts the original back. Assigning jest.fn() loses the original, so restoring it is the test's own job.

open as a page

In Jest 30, how do you make a jest.fn() mock return different values on successive calls, such as a charge that fails once then succeeds?

level: juniorimportance: should knowfreq 60%

basics

~20 s

Chain the Once helpers, such as mockRejectedValueOnce then mockResolvedValueOnce: each queues one result, consumed in order. When the queue is empty the mock falls back to its default from mockReturnValue, mockResolvedValue or mockImplementation, or returns undefined.

open as a page

In a Jest 30 test file, why does jest.mock(path, factory) apply before the imports above it, and what limits does that set on the factory?

level: middleimportance: should knowfreq 58%

basics

~20 s

babel-jest hoists jest.mock above the file's imports, so every importer gets the mock. The factory may use only its own locals, allowed globals, pure constants and names prefixed mock, and a mock-prefixed variable must be initialised before the factory first runs.

open as a page

Why would a Jest 30 order-service test pass alone but fail after the other tests in its file, and how do you trace and fix the leftover mock state?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Mocks live for the whole test file, so call records, unused Once values, implementations and installed spies carry into later tests. Reproduce with --randomize and a seed, compare the mock's state, then reset in beforeEach or enable clearMocks with restoreMocks.

open as a page