How to pass an object to expect().toBeCalledWith() with Jest?

Sometimes, we want to pass an object to expect().toBeCalledWith() with Jest.

In this article, we’ll look at how to pass an object to expect().toBeCalledWith() with Jest.

How to pass an object to expect().toBeCalledWith() with Jest?

To pass an object to expect().toBeCalledWith() with Jest, we should use the object as the argument of the expect.objectContaining method.

For instance, we write:

expect(api.submitForm).toBeCalledWith(
  expect.objectContaining({
    foo: 'foo',
    bar: 'bar'
  }),
);

to call expect.objectContaining with the object that we want to check api.submitForm is called with.

api.submitForm is the function being spied on.

Conclusion

To pass an object to expect().toBeCalledWith() with Jest, we should use the object as the argument of the expect.objectContaining method.