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

Nad*_*ham 9 javascript reactjs jestjs

我正在使用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);
  });
Run Code Online (Sandbox Code Playgroud)

错误消息将是这样的

Expected mock function to have been called with:
      [{"bar": "bar", "foo": "foo"}]
    But it was called with:
      [{"bar": "bar", "foo": "foo"}]
Run Code Online (Sandbox Code Playgroud)

更新

看来下面的代码工作正常

  expect(api.submitForm).toBeCalledWith(
    expect.objectContaining({
     foo : 'foo',
      bar: 'bar'
    }),
  );
Run Code Online (Sandbox Code Playgroud)

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

const obj = {
  foo : ['foo1', 'foo2'],
  bar: 'bar'
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*off 13

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

 expect(api.submitForm).toBeCalledWith(
    expect.objectContaining({
     foo : 'foo',
      bar: 'bar'
    }),
  );
Run Code Online (Sandbox Code Playgroud)

  • 这实际上工作正常,但是如果您的对象包含数组属性,则会出现问题 (4认同)

ya_*_*mon 8

您可以使用.mock.calls[callIdx][paramIdx]
描述+示例:https ://stackoverflow.com/a/41939921/2519073

在你的情况下

expect(api.submitForm.mock.calls[0][0]).toMatchObject( // use whatever matcher you want
    {
      foo : ['foo1', 'foo2'],
      bar: 'bar'
    },
  );
Run Code Online (Sandbox Code Playgroud)