In Jest 30, what does a jest.fn() mock function record about its calls, and which matchers read that record back?
answer
- a record kept on the function
- one property holds the history
- arguments, outcomes, this values, instances
- toHave... primary matcher names
basics
~20 sA 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 linesfunction 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
Know that jest.fn() records calls on its mock property and name the main matchers: toHaveBeenCalled, toHaveBeenCalledTimes and toHaveBeenCalledWith, in their Jest 30 spelling.
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.
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.
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.