How can I get the arguments called in jest mock function?
I want to inspect the object that is passed as argument.
How can I get the arguments called in jest mock function?
I want to inspect the object that is passed as argument.
Just use mockObject.calls. In my case I used:
const call = mockUpload.mock.calls[0][0]
Here's the documentation about the mock
property
Here is a simple way to assert the parameter passed.
expect(mockedFunction).toHaveBeenCalledWith("param1","param2");
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}...`);
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')
Use an argument captor, something like this:
let barArgCaptor;
const appendChildMock = jest
.spyOn(foo, "bar")
.mockImplementation(
(arg) => (barArgCaptor = arg)
);
Then you could expect
on the captor's properties to your heart's content:
expect(barArgCaptor.property1).toEqual("Fool of a Took!");
expect(barArgCaptor.property2).toEqual(true);
I find I often want to validate the exact arguments of exact calls to my mock functions; my approach is:
let mockFn = jest.fn((/* ... */) => { /* ... */ });
// ... do some testing which triggers `mockFn` ...
expect(mockFn.mock.calls).toEqual([
// Ensure `mockFn` was called exactly 3 times:
// The 1st time with arguments "a" and 1,
[ 'a', 1 ],
// 2nd time with arguments "b" and 2,
[ 'b', 2 ],
// 3rd time with arguments "c" and 3
[ 'c', 3 ]
]);
we can add a mockImplementation to the mock method and have it return the arguments back which can be used to evaluate.