77

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'
}
brass monkey
  • 5,841
  • 10
  • 36
  • 61
Nader Hisham
  • 5,214
  • 4
  • 19
  • 35

3 Answers3

91

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'
    }),
  );
Matt_Bro
  • 14,062
  • 2
  • 28
  • 41
Kevin Amiranoff
  • 13,440
  • 11
  • 59
  • 90
8

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'
    },
  );
ya_dimon
  • 3,483
  • 3
  • 31
  • 42
3

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'
   })
);
vanduc1102
  • 5,769
  • 1
  • 46
  • 43