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

Mor*_*sis 7 javascript reactjs jestjs material-ui react-testing-library

我目前正在尝试在我的 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);
})
Run Code Online (Sandbox Code Playgroud)

将绑定closeDialog方法传递给子组件时出现相同或类似的问题。它似乎未经测试。我将如何测试这个/如果它触发方法(在子组件上),它是否会被子组件的测试覆盖,我还没有创建子组件测试。

在此处输入图片说明

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

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

Dav*_*haw 0

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

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