Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest passing an object to expect().toBeCalledWith()

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"}] 

Update

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' } 
like image 329
Nader Hisham Avatar asked Dec 23 '17 14:12

Nader Hisham


People also ask

How do you expect a function in Jest?

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()).

What is expect assertions in Jest?

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.

How do you check if a function is called in Jest?

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.


1 Answers

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'     }),   ); 
like image 154
Kevin Amiranoff Avatar answered Sep 18 '22 12:09

Kevin Amiranoff