【问题标题】:react-testing-library queryByTestId returning NULL反应测试库 queryByTestId 返回 NULL
【发布时间】:2019-07-30 00:54:25
【问题描述】:

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

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

从this article 和this article 中获取线索,我将data-testid 属性添加到我的孩子,然后我使用getByTestId 和queryByTestId。但是,由于某种原因,我的查询没有找到据我所知存在的子节点。

我的测试设置有什么问题,还是我误解了应该如何使用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();
  });
});

【问题讨论】:

    标签: reactjs jestjs react-testing-library


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-09-03
      • 2015-11-23
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多