How to mock the same function twice with different arguments with Jest?

Sometimes, we want to mock the same function twice with different arguments with Jest.

In this article, we’ll look at how to mock the same function twice with different arguments with Jest.

How to mock the same function twice with different arguments with Jest?

To mock the same function twice with different arguments with Jest, we can call mockReturnValueOnce.

For instance, we write:

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

to call mockReturnValueOnce on the mocked function myMock to return the values we want.

If we just want to check the argument that a mocked function is called with, we use

expect(mock).toHaveBeenNthCalledWith(1, 'foo');

to check the argument at position 1 is called with 'foo with toHaveBeenNthCalledWith.

Conclusion

To mock the same function twice with different arguments with Jest, we can call mockReturnValueOnce.