Categories
JavaScript Answers

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

Spread the love

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

For instance, we write

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

to call mockReturnValueOnce on the myMock mock object.

Then we call mockReturnValue again to return a different mock value for a different call.

Finally, we call mockReturnValue to return a 3rd value for myMock.

Then we can check them with

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

to check with the arguments that mock is called with in different calls.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *