An extended, sugary way to mock return values for specific arguments only
Many thanks to @jonasholtkamp. He forked this repo when I was inactive and stewarded several key features and bug fixes!
jest-when allows you to use a set of the original
Jest mock functions in order to train
your mocks only based on parameters your mocked function is called with.
An example statement would be as follows:
The trained mock function
fn will now behave as follows -- assumed no other trainings took place:
yay!if called with
1as first parameter
undefinedif called with any other first parameter than
For extended usage see the examples below.
The supported set of mock functions is:
npm i --save-dev jest-when
const fn = jest
Supports chaining of mock trainings:
Thanks to @fkloes.
Thanks to @danielhusar.
Supports replacement of mock trainings:
This replacement of the training does only happen for mock functions not ending in
mockReturnValueOnce are removed after a matching function call anyway.
Thanks to @fkloes.
Supports multiple args with partial argument matching:
Supports training for single calls
Supports Promises, both resolved and rejected
await resolvesawait resolvesawait resolvesawait rejectsawait rejectsawait rejects
const theSpiedMethod = jest;;const returnValue = theInstance;;
Supports jest matchers:
const result =
Supports compound declarations:
Assert the args:
expectCalledWith instead to run an assertion that the
fn was called with the provided
args. Your test will fail if the jest mock function is ever called without those exact
Disclaimer: This won't really work very well with compound declarations, because one of them will always fail, and throw an assertion error.
; // Will throw a helpful jest assertion error with args diff
Supports default behavior
Use any of
mockImplementation directly on the object
to set up a default behavior, which will serve as fallback if no matcher fits.
Supports custom mockImplementation
You could use this to call callbacks passed to your mock fn or other custom functionality.
const cb = jest
Thanks to @idan-at.
Supports reseting mocks between tests
You could use this to prevent mocks from carrying state between tests or assertions.
const when resetAllWhenMocks =const fn = jest
Thanks to @whoaa512.
Supports verifying that all mocked functions were called
verifyAllWhenMocksCalled after your test to assert that all mocks were used.
const when verifyAllWhenMocksCalled =const fn = jest// passes
const when verifyAllWhenMocksCalled =const fn = jest// fails
Thanks to @roaclark.