【问题标题】:Test a onClose callback from dialog when using material UI & react testing library?使用材质 UI 和反应测试库时从对话框测试 onClose 回调?
【发布时间】:2020-02-20 13:25:33
【问题描述】:

我目前正在尝试在我的 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。

【问题讨论】:

    标签: javascript reactjs jestjs material-ui react-testing-library


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 第二条包含了一个不去掉箭头函数的解决方案,第一篇似乎编译的小争论,但似乎主要是个人喜好?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2020-03-10
      • 2021-08-04
      • 1970-01-01
      • 2020-01-21
      • 2021-04-07
      • 1970-01-01
      相关资源
      最近更新 更多