Jest将对象传递给expect()。toBeCalledWith()

时间:2017-12-23 14:30:37

标签: javascript reactjs jest

我正在使用jest来测试我的反应组件,并且我正在使用expect(...).toBeCalledWith(...);测试是否已使用特定参数调用函数,并且它对值类型工作正常。

问题是我想测试一个将对象作为参数的函数,所以当你调用expect(myFunc).toBeCalledWith(object);时,测试总是失败,因为当然两个对象相互比较没有相同的引用。

那我怎么解决这个问题呢?

我正在尝试测试的示例代码是

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);
  });

错误信息就是这样的

Expected mock function to have been called with:
      [{"bar": "bar", "foo": "foo"}]
    But it was called with:
      [{"bar": "bar", "foo": "foo"}]

更新

以下代码似乎正常

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

但是,如果对象包含具有数组值的属性,则上述解决方案不起作用

const obj = {
  foo : ['foo1', 'foo2'],
  bar: 'bar'
}

1 个答案:

答案 0 :(得分:7)

查看jest doc(https://facebook.github.io/jest/docs/en/expect.html#expectobjectcontainingobject)。看来你可以这样做:

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