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

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

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



Solution 1:[1]

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:[2]

Here is a simple way to assert the parameter passed.

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

Solution 3:[3]

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:[4]

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')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jmrah
Solution 2 Kitson
Solution 3 Jeremiah Flaga
Solution 4 NearHuscarl