为了账号安全,请及时绑定邮箱和手机立即绑定

使用材质 UI 和反应测试库时从对话框测试 onClose 回调?

使用材质 UI 和反应测试库时从对话框测试 onClose 回调?

潇湘沐 2021-12-02 14:59:24
我目前正在尝试在我的 React 应用程序上获得完整的测试覆盖率,但是在尝试测试来自 Material UI 组件的回调事件参数时,我遇到了笑话。我认为通过测试转义事件我可以覆盖onClose参数,但它仍然显示为未经测试。该测试的示例:function renderWithRedux(  ui: any,  startingState: any = initialState,  store?: any) {  if (!store) {    store = createStore(reducer, startingState);  }  return {    ...render(<Provider store={store}>{ui}</Provider>),    // adding `store` to the returned utilities to allow us    // to reference it in our tests (just try to avoid using    // this to test implementation details).    store,  };}test("Should close the dialog on exit event eg esc key pressed", () => {  const { container, queryByTestId } = renderWithRedux(    <PermissionGroupList />,    permissionGroupCat  );  fireEvent(    queryByTestId("add-group"),    new MouseEvent("click", {      bubbles: true,      cancelable: true,    })  );  let dialogBox = queryByTestId("add-group-dialog");  // Check that the dialog is open.  expect(dialogBox).toBeTruthy();  // Check that the dialog it closes.  fireEvent.keyDown(document.body, {    key: "Escape",    keyCode: 27,    which: 27  })  setTimeout(() => {    // Try to re get the element.    dialogBox = queryByTestId("add-group-dialog");    expect(dialogBox).toBeNull();  }, 500);})将绑定closeDialog方法传递给子组件时出现相同或类似的问题。它似乎未经测试。我将如何测试这个/如果它触发方法(在子组件上),它是否会被子组件的测试覆盖,我还没有创建子组件测试。正如您在上面的屏幕截图中所看到的,这两行都未经测试,所以我如何用我的测试来覆盖这些。我正在使用 react-testing-library 和 jest --coverage 与 redux 和 react-redux。
查看完整描述

2 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

我建议不要创建箭头函数作为道具。以下是对缺点和替代方法的更详细说明:https : //medium.com/@oleg008/arrow-functions-in-react-f782d11460b4

这也将使您的测试涵盖这些道具。尽管您可能还需要测试handleGroupDialog是否调用了类方法。你可以用间谍来做到这一点:https : //remarkablemark.org/blog/2018/06/13/spyon-react-class-method/

大卫也说得对!您将需要使用 done 方法或将您的测试转换为异步并等待。


查看完整回答
反对 回复 2021-12-02
?
蓝山帝景

TA贡献1843条经验 获得超7个赞

您在同步测试中运行的异步代码。如果您setTimeout在测试中使用,那么您需要传入一个done()函数,然后在最后一个异步事件完成时调用它。

https://jestjs.io/docs/en/asynchronous


查看完整回答
反对 回复 2021-12-02
  • 2 回答
  • 0 关注
  • 148 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信