Jest mock the same function twice with different arguments

1- If you want the mock to return different results on each call:

Use mockReturnValueOnce

myMock
  .mockReturnValueOnce(10)
  .mockReturnValueOnce('x')
  .mockReturnValue(true);

will return 10 on the first call, 'x' on the second call and true anytime after that.

2- If you want to check the arguments that the mock has been called with:

Use toHaveBeenNthCalledWith

expect(mock).toHaveBeenNthCalledWith(1, '1st call args');
expect(mock).toHaveBeenNthCalledWith(2, '2nd call arg 1', '2nd call arg 2');

will assert that

  • the mock was called with '1st call args' the first time it was called -> mock('1st call args')

  • the mock was called with '2nd call arg 1' and '2nd call arg 2' the second time it was called -> mock('2nd call arg 1', '2nd call arg 2')

3- If you want a specific response based on the function parameter

It is not supported by jest by default but you can have a look at jest-when which allows you to do something like:

when(fn).calledWith(1).mockReturnValue('yay!')