Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jest将对象传递给expect().toBeCalledWith()_Javascript_Reactjs_Jestjs - Fatal编程技术网

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

Javascript Jest将对象传递给expect().toBeCalledWith(),javascript,reactjs,jestjs,Javascript,Reactjs,Jestjs,我使用jest测试我的react组件,我使用expect(…).toBeCalledWith(…)测试是否使用特定参数调用了函数,并且该函数可以很好地处理值类型 问题是我想测试一个以object作为参数的函数,所以当您调用expect(myFunc).toBeCalledWith(object)测试总是失败,因为两个相互比较的对象没有相同的引用 那么我该如何解决这个问题呢 我要测试的示例代码是 it('the function should be called with the correct

我使用jest测试我的react组件,我使用
expect(…).toBeCalledWith(…)
测试是否使用特定参数调用了函数,并且该函数可以很好地处理值类型

问题是我想测试一个以object作为参数的函数,所以当您调用
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);
  });
更新 下面的代码似乎可以正常工作

  expect(api.submitForm).toBeCalledWith(
    expect.objectContaining({
     foo : 'foo',
      bar: 'bar'
    }),
  );
但是,如果对象包含具有数组值的属性,则上述解决方案不起作用

const obj = {
  foo : ['foo1', 'foo2'],
  bar: 'bar'
}
看看jest doc()。看起来你可以这样做:

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

问题可能是别的。我在我的代码中使用了上述模式,它与jest版本的预期一样有效……此处的jest文档本身表明,它们是在比较值,而不是参考值,我使用的是jest
20.0.4
,如果你的对象中有一个数组属性,问题就会出现。第二个解决方案现在起作用了。我在代码中发现了一个输入错误。这会起作用的。但是expect.objectContaining的真正意图略有不同。实际上,这很好,但是如果对象包含数组属性,问题就来了
 expect(api.submitForm).toBeCalledWith(
    expect.objectContaining({
     foo : 'foo',
      bar: 'bar'
    }),
  );