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

错误消息可能是这样的

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'
}

推荐答案

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

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

Reactjs相关问答推荐

Reaction路由的问题-在Effect使用API调用响应设置状态之前呈现页面

如何创建react router v6的自定义子路由?

如何使数据库数据在第一次呈现时显示?

TanStack/Reaction-Query在我的Vercel应用程序中不起作用

当我try 部署我的Reaction应用程序时,为什么在此PrevState语句中收到语法错误?

折叠并重新打开react 手风琴将重置内部状态

REACTION-Easy-SORT返回.map错误

在 useSelector() 中使用 array.map() 如何导致组件在分派操作时重新渲染?

React Router 6 点击链接在 React 18 应用中打开 flickr 页面

如何使用 redux 和 react-plotly.js

将 useState 设置为组件内部的值

如何通过onpress on view in react native flatlist来降低和增加特定视图的高度?

将路径数组传递给Route会引发错误

如何在 MUI 数据网格中的 renderCell 组件之间传递状态

需要帮助在 document.queryselector 的 nextjs 页面上插入 useEffect 状态

React 检测哪些 props 在 useEffect 触发器上发生了变化

如何用实际的br标签替换axios响应中的br标签?

React Hooks 表单在日志(log)中显示未定义的用户名

Rtk 查询无效标签不使数据无效

Cypress 中的 process.env 空对象