Reputation: 5414
I'm using jest to test my react components and I'm using expect(...).toBeCalledWith(...);
to test if a function has been called with specific parameters, and it works fine with value types.
The problem is I want to test a function that takes object as a parameter so when you call expect(myFunc).toBeCalledWith(object);
the test always fails because of course the two object compared to each other do not have the same reference.
so how can I solve this problem ?
a sample code of what I'm trying to test is
it('the function should be called with the correct object', () => {
api.submitForm = jest.fn().mockReturnValue(Promise.resolve());
const wrapper = shallow(<component />);
const instance = wrapper.instance();
instance.submitForm();
const object = {
foo : 'foo',
bar: 'bar'
};
// this always fails even the function is called with the same object values
expect(api.submitForm).toBeCalledWith(object);
});
An error message would be something like this
Expected mock function to have been called with:
[{"bar": "bar", "foo": "foo"}]
But it was called with:
[{"bar": "bar", "foo": "foo"}]
it seems the below code works fine
expect(api.submitForm).toBeCalledWith(
expect.objectContaining({
foo : 'foo',
bar: 'bar'
}),
);
however, if the object contains a property with array value, the above solution doesn't work
const obj = {
foo : ['foo1', 'foo2'],
bar: 'bar'
}
Upvotes: 90
Views: 123025
Reputation: 14468
Looking at the jest doc (https://jestjs.io/docs/expect#expectobjectcontainingobject). It seems you can do something like this:
expect(api.submitForm).toBeCalledWith(
expect.objectContaining({
foo : 'foo',
bar: 'bar'
}),
);
Upvotes: 109
Reputation: 6245
In case you your function is called with arguments
function update( userId, partialUserObject ){
// update logic
}
You can use
expect(update).toBeCalledWith('mockUserId',
expect.objectContaining({
username:'hello-world',
displayName: 'Hello World'
})
);
Upvotes: 5
Reputation: 3822
you can use .mock.calls[callIdx][paramIdx]
description + example: https://stackoverflow.com/a/41939921/2519073
in your case
expect(api.submitForm.mock.calls[0][0]).toMatchObject( // use whatever matcher you want
{
foo : ['foo1', 'foo2'],
bar: 'bar'
},
);
Upvotes: 10