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?
answer
- a queue before a default
- first in, first out
- the Once suffix
- resolved and rejected shorthands
basics
~20 sChain 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.
solid answer
~40 sEvery `jest.fn()` has an optional default implementation plus a queue of one-shot ones. `mockReturnValue`, `mockResolvedValue`, `mockRejectedValue` and `mockImplementation` set the default; the `...Once` forms push one entry onto the queue. A call takes the next queued entry first, in the order they were added, and only when the queue is empty does it use the default, or return `undefined` if there is none. So a charge that fails once and then succeeds is `jest.fn().mockRejectedValueOnce(new Error('gateway_timeout')).mockResolvedValue({ id: 'rcpt_2' })`. `mockResolvedValue(v)` is shorthand for an implementation returning `Promise.resolve(v)`, and `mockReturnValue(v)` returns the very same `v` on every call. Jest 30.5 also added `whenCalledWith(...)` to pick a value by argument list.
code
javascript · 20 linesasync function placeOrderWithRetry(order, charge) {
try {
return await charge(order.id, order.totalCents);
} catch {
return charge(order.id, order.totalCents);
}
}
test('a failed first charge is retried once', async () => {
const charge = jest
.fn()
.mockRejectedValueOnce(new Error('gateway_timeout'))
.mockResolvedValue({ id: 'rcpt_2' });
const receipt = await placeOrderWithRetry({ id: 'ord_7', totalCents: 1500 }, charge);
expect(receipt).toEqual({ id: 'rcpt_2' });
expect(charge).toHaveBeenCalledTimes(2);
expect(charge).toHaveBeenNthCalledWith(2, 'ord_7', 1500);
});go deeper
Recall the helper names and the Once suffix, and that a mock with nothing configured returns undefined.
Explain the once queue versus the default implementation, why the queue drains in order, and which helpers are shorthands for which implementation.
Spot scripted mocks that drift from reality, such as a shared mutable return value or a synchronous throw standing in for a rejected promise, and fix them.
Decide when scripted return values stop paying off and a small hand-written fake of the payment client would keep tests clearer and cheaper to maintain.
## The default and the queue A Jest mock function decides what to return from two places. The **default implementation** is used on every call; it is set by `jest.fn(impl)`, by `mockImplementation(fn)`, or by one of the shorthands below. The **once queue** holds one-shot implementations added by the `...Once` helpers. Each call works through a fixed order: 1. If the once queue is not empty, take the oldest entry, remove it from the queue, and run it. 2. Otherwise run the default implementation, if one has been set. 3. Otherwise return `undefined`. Because the queue is first in, first out, chained `...Once` calls describe a script: the first call gets the first value, the second call the second, and so on. Setting a new default with `mockReturnValue` or `mockImplementation` replaces the old default, while the queue keeps whatever is still waiting in it. ## The shorthand helpers Every value helper is sugar over an implementation, which is why they can be mixed freely in one chain. | Helper | Equivalent implementation | Applies to | |---|---|---| | `mockReturnValue(v)` | `() => v` | every call (default) | | `mockReturnValueOnce(v)` | `() => v` | the next queued call | | `mockResolvedValue(v)` | `() => Promise.resolve(v)` | every call (default) | | `mockResolvedValueOnce(v)` | `() => Promise.resolve(v)` | the next queued call | | `mockRejectedValue(e)` | `() => Promise.reject(e)` | every call (default) | | `mockRejectedValueOnce(e)` | `() => Promise.reject(e)` | the next queued call | | `mockImplementation(fn)` | `fn` | every call (default) | | `mockImplementationOnce(fn)` | `fn` | the next queued call | `mockReturnThis()` is one more shorthand, for a function that returns `this`, which suits chained builder APIs. ## Scripting a failure, then a success An order service that retries a failed payment once is the textbook case. The test wants the first `charge` call to reject and every later call to resolve: - `mockRejectedValueOnce(new Error('gateway_timeout'))` queues one rejection. - `mockResolvedValue({ id: 'rcpt_2' })` sets the default for everything after it. - `toHaveBeenCalledTimes(2)` and `toHaveBeenNthCalledWith(2, ...)` then confirm that the retry happened and what it sent. The order of the chain matters less than the kind of helper: a `...Once` value always runs before the default, even if the default was set first. If the code makes more calls than the script covers, the extra calls get the default, and with no default they get `undefined`, which tends to surface as a confusing error deep inside the order service rather than as a clear test failure. ## Choosing the right helper - **Async callers want promise helpers.** `mockResolvedValue` and `mockRejectedValue` return promises, which is what an `await` expects. `mockImplementationOnce(() => { throw err; })` throws synchronously instead, which is a different behaviour: code that calls `.catch()` on the result never receives a promise at all. - **`mockResolvedValue(new Error(...))` resolves.** Passing an error object to the resolved helper hands the caller a fulfilled promise whose value happens to be an error; only `mockRejectedValue` produces a rejection. - **`mockReturnValue` shares one reference.** The value is captured once, so every call returns the same object. If the code under test mutates it, later calls see the mutation; use `mockImplementation(() => ({ items: [] }))` to build a fresh object per call. - **`jest.fn(impl)` is only a default.** Passing an implementation to `jest.fn` sets the same default that `mockImplementation` sets, so a later `mockReturnValue` replaces it, and `getMockImplementation()` returns whichever default is current. - **Computed results need an implementation.** When the return value depends on the arguments, for example a fee that depends on the amount, write `mockImplementation((orderId, amountCents) => ...)`. ## Temporary and per-argument behaviour Two helpers avoid rewriting the default for a narrow case: - **`withImplementation(fn, callback)`** swaps the implementation only while `callback` runs, then puts the previous one back. If the callback is async it returns a promise, and awaiting it restores the implementation after the callback finishes. - **`whenCalledWith(...args)`**, added in **Jest 30.5**, returns a sub-mock that only answers calls whose arguments match, using the same equality and asymmetric matchers as `toHaveBeenCalledWith`. `charge.whenCalledWith('ord_big', expect.any(Number)).mockRejectedValue(new Error('limit'))` rejects for one order and leaves every other call to the base mock. Its precedence puts the base mock's own once queue first, then matching branches, then the base default. Whatever the helper, the call record is unaffected: every call still lands in `mock.calls` and `mock.results`, so the same test can script the returns and then assert on what was sent.
- What does a jest.fn() return once its queued Once values run out and no default was ever set?It returns `undefined`. The once queue is consulted first, then the default implementation, and with neither present the call simply returns `undefined` while still being recorded in `mock.calls`. That is why a test that queues too few values often fails with a confusing `undefined` deep inside the code under test.
- How would you make the same mock reject for one order id but resolve for all others in Jest 30.5?Set the default with `mockResolvedValue(...)`, then register `charge.whenCalledWith('ord_big', expect.any(Number)).mockRejectedValue(new Error('limit'))`. Calls matching those arguments route to the sub-mock; every other call falls through to the base default. Before 30.5 the same effect was usually written as a branching `mockImplementation`.
- mockReturnValueOnce replaces the default for every later call.
- Queued Once values are consumed last-in, first-out.
- mockResolvedValue(new Error('x')) makes the mock reject.
- mockReturnValue hands each call a fresh copy of the object.
- A default set before the Once helpers runs ahead of the queued values.
Assumes Jest 30.5, which added mockFn.whenCalledWith for argument-specific return values; the Once queue and the value shorthands work the same across Jest 30.