1

我正在测试一个简单的 Modal 组件,它是 reactstrap 组件的包装器。我正在使用@testing-library/react。它在浏览器中工作正常,但在测试过程中,我发现即使卸载后模态永久存在于 DOM 中。

expect(props.toggleModal).toHaveBeenCalled();

上述断言效果很好。所以我们可以保证这个函数已经被调用并且modal状态已经从真变为假。

我签入了我的模态组件,这是正确的。所以不应该显示模态(它在浏览器中工作)。

/* eslint-disable react/prop-types */
import React, { useState } from "react";
import { render, fireEvent, cleanup } from "@testing-library/react";
import Modal from "./";

afterEach(cleanup);
const props = {
  toggleModal: jest.fn(),
  title: "Fake title",
  body: (
    <div>
      <p>Fake body</p>
    </div>
  ),
  footer: (
    <ul>
      <li>Link 1</li>
      <li>Link 2</li>
    </ul>
  )
};

function App() {
  const [modal, setModal] = useState(true);
  props.toggleModal.mockImplementation(() => setModal(prevModal => !prevModal));
  return (
    <div id="app">
      <Modal {...props} isOpen={modal} />
    </div>
  );
}

test("renders Modal component", () => {
  const { getByText, getAllByText } = render(<App />);
  expect(getByText("Fake body")).toBeTruthy();
  expect(getAllByText("Link", { exact: false })).toHaveLength(2);
  fireEvent.click(document.querySelector("button"));
  expect(props.toggleModal).toHaveBeenCalled();
  console.log(document.body.innerHTML);
});
//Modal.js
import React from "react";
import PropTypes from "prop-types";
import {
  Modal as BootstrapModal,
  ModalHeader,
  ModalBody,
  ModalFooter
} from "reactstrap";
class Modal extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <BootstrapModal
        isOpen={this.props.isOpen}
        toggle={this.props.toggleModal}
      >
        {this.props.title && (
          <ModalHeader toggle={this.props.toggleModal}>
            {this.props.title}
          </ModalHeader>
        )}
        {this.props.body && <ModalBody>{this.props.body}</ModalBody>}
        {this.props.footer && <ModalFooter>{this.props.footer}</ModalFooter>}
      </BootstrapModal>
    );
  }

  static propTypes = {
    isOpen: PropTypes.bool,
    title: PropTypes.string,
    body: PropTypes.element,
    footer: PropTypes.element,
    toggleModal: PropTypes.func
  };
}

export default Modal;

我认为 DOM 中不应该存在模态,所以在这个例子中 document.body.innerHTML 应该只有<div><div id="app"></div></div>

4

0 回答 0