How can I get the arguments called in jest mock function?

JavascriptJestjs

Javascript Problem Overview


How can I get the arguments called in jest mock function?

I want to inspect the object that is passed as argument.

Javascript Solutions


Solution 1 - Javascript

Just use mockObject.calls. In my case I used:

const call = mockUpload.mock.calls[0][0]

Here's the documentation about the mock property

Solution 2 - Javascript

Here is a simple way to assert the parameter passed.

expect(mockedFunction).toHaveBeenCalledWith("param1","param2");

Solution 3 - Javascript

You can use toHaveBeenCalledWith() together with expect.stringContaining or expect.arrayContaining() or expect.objectContaining()

...
const { host } = new URL(url);
expect(mockedFunction).toHaveBeenCalledWith("param1", expect.stringContaining(`http://${host}...`);

Solution 4 - Javascript

I prefer lastCalledWith() over toHaveBeenCalledWith(). They are both the same but the former is shorter and help me reduce the cognitive load when reading code.

expect(mockedFn).lastCalledWith('arg1', 'arg2')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBruno QuaresmaView Question on Stackoverflow
Solution 1 - JavascriptBruno QuaresmaView Answer on Stackoverflow
Solution 2 - JavascriptSenthil Arumugam SPView Answer on Stackoverflow
Solution 3 - JavascriptJeremiah FlagaView Answer on Stackoverflow
Solution 4 - JavascriptNearHuscarlView Answer on Stackoverflow