react-testing-library queryByTestId 返回 NULL

react-testing-library queryByTestId returning NULL

我正在从使用 enzyme 切换到 react-testing-library 来测试我的组件。

我有一个简单的组件 CustomModal,它的作用很像 reactstrapModal 的包装器。 我正在尝试测试我的 CustomModal 是否包含它应该包含的 child 元素。

根据 this article and this article 的提示,我将 data-testid 属性添加到我的 children,然后我使用 getByTestIdqueryByTestId。但是,出于某种原因,我的查询没有找到据我所知存在的 child 个节点。

是我的测试设置有问题,还是我误解了应该如何使用 react-testing-library

可以在这个 CodeSandbox 中找到基本代码以及测试(失败):

我的基本 CustomModal 组件如下所示:

/*
 * src/components/CustomModal/index.js
 */

import React from "react";
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";

const getSanitizedModalProps = props => {
  let modalProps = { ...props };
  delete modalProps.onConfirm;
  delete modalProps.onCancel;
  delete modalProps.headerText;
  delete modalProps.children;
  modalProps.isOpen = modalProps.isOpen === true;
  return modalProps;
};

export default props => {
  return (
    <Modal data-testid="modal" {...getSanitizedModalProps(props)}>
      <ModalHeader data-testid="modal-header">{props.headerText}</ModalHeader>
      <ModalBody data-testid="modal-body">{props.children}</ModalBody>
      <ModalFooter data-testid="modal-footer">
        <Button data-testid="confirm-button" onClick={props.onConfirm}>
          Confirm
        </Button>
        <Button data-testid="cancel-button" onClick={props.onCancel}>
          Cancel
        </Button>
      </ModalFooter>
    </Modal>
  );
};

我的测试文件如下所示:

/*
 * src/components/CustomModal/CustomModal.test.js
 */

import React from "react";
import { render } from "react-testing-library";
import CustomModal from "./index";

const TEST_IDS = {
  modal: "modal",
  header: "modal-header",
  body: "modal-body",
  footer: "modal-footer",
  cancel: "cancel-button",
  confirm: "confirm-button"
};

describe("<Modal />", () => {
  const headerText = "hello world";
  it("renders all of the children", () => {
    const { queryByTestId } = render(<CustomModal headerText={headerText} />);

    // The following assertions all fail
    expect(queryByTestId(TEST_IDS.modal)).toBeTruthy(); 
    expect(queryByTestId(TEST_IDS.header)).toBeTruthy();
    expect(queryByTestId(TEST_IDS.body)).toBeTruthy();
    expect(queryByTestId(TEST_IDS.footer)).toBeTruthy();
    expect(queryByTestId(TEST_IDS.cancel)).toBeTruthy();
    expect(queryByTestId(TEST_IDS.confirm)).toBeTruthy();
  });
});

您的模式已关闭,您需要将isOpen传递给它:

render(<CustomModal headerText={headerText} isOpen />);