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

我目前正在尝试在我的 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方法传递给子组件时出现相同或类似的问题。它似乎未经测试。我将如何测试这个/如果它触发方法(在子组件上),它是否会被子组件的测试覆盖,我还没有创建子组件测试。

http://img3.mukewang.com/61a86ee00001164004430115.jpg

正如您在上面的屏幕截图中所看到的,这两行都未经测试,所以我如何用我的测试来覆盖这些。

我正在使用 react-testing-library 和 jest --coverage 与 redux 和 react-redux。


潇湘沐
浏览 149回答 2
2回答

海绵宝宝撒

我建议不要创建箭头函数作为道具。以下是对缺点和替代方法的更详细说明:https&nbsp;:&nbsp;//medium.com/@oleg008/arrow-functions-in-react-f782d11460b4这也将使您的测试涵盖这些道具。尽管您可能还需要测试handleGroupDialog是否调用了类方法。你可以用间谍来做到这一点:https&nbsp;:&nbsp;//remarkablemark.org/blog/2018/06/13/spyon-react-class-method/大卫也说得对!您将需要使用 done 方法或将您的测试转换为异步并等待。

蓝山帝景

您在同步测试中运行的异步代码。如果您setTimeout在测试中使用,那么您需要传入一个done()函数,然后在最后一个异步事件完成时调用它。https://jestjs.io/docs/en/asynchronous
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript