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
Tuple type '[]' of length '0' has no element at index '0'. on the second 0, you can get around it by using const call = (mockUpload.mock.calls[0] as any[])[0];.jest.fn(() => "foobar"), but not when you just use jest.fn(), in this case calls is of type any (instead of being an array potentially empty).jest.fn((args) => "foobar"): explicitely defining args will results in a better typings, and mock.calls[0][0] will be accepted by TypeScript. This is because if you use 2 args in your mock, mock.calls[0] is an array of length 2. If you use 1 arg, length 1, and 0 args => length 0. So in your mock just use the same number of arguments as your function is expecting, even if you don't use them.Tuple type '[]' of length '0' has no element at index '0'. error: in my case, I had typed my mock using SpyInstance without understanding the two generic parameters for that type. SpyInstance<R, A> takes the return type R and an array of argument types A. Specifying a type of SpyInstance<unknown, [...unknown[]]> allowed me to get any number of arguments from the calls of my mock without any errors.Here is a simple way to assert the parameter passed.
expect(mockedFunction).toHaveBeenCalledWith("param1","param2");
mockUpload.mock.calls[0]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}...`);
expect.anything() on it.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 ]
]);
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')
we can add a mockImplementation to the mock method and have it return the arguments back which can be used to evaluate.