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' }
The expect function is used every time you want to test a value. You will rarely call expect by itself. Instead, you will use expect along with a "matcher" function to assert something about a value. expect(bestLaCroixFlavor()).
This is from Jest documentation: Expect. assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.
To check if a component's method is called, we can use the jest. spyOn method to check if it's called. We check if the onclick method is called if we get the p element and call it.
Looking at the jest doc (https://facebook.github.io/jest/docs/en/expect.html#expectobjectcontainingobject). It seems you can do something like this:
expect(api.submitForm).toBeCalledWith( expect.objectContaining({ foo : 'foo', bar: 'bar' }), );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With