有没有办法用 react-test-renderer 测试 Chakra-ui 模态对话框?

Is there a way to test Chakra-ui modal dialogs with react-test-renderer?

我正拼命地尝试测试一个模态,但无法理解它!

这是我所在的位置:

expect(
  create(
    <PortalManager>
      <Modal isOpen={true} onClose={jest.fn()}>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Modal Title</ModalHeader>
          <ModalCloseButton />
          <ModalBody>Modal body</ModalBody>
          <ModalFooter>Modal footer</ModalFooter>
        </ModalContent>
      </Modal>
    </PortalManager>,
  ).toJSON(),
).toMatchSnapshot();

我强制打开了模式。我在它周围添加了 PortalManager 以确保 Chakra 知道在哪里放置模态但快照总是空的。

好吧,一个选项可能是模拟 PortalManager 本身并使其表现得像 React.Component 而不是 React.ReactPortal,所以像

const divWithChildrenMock = (children, identifier) => <div data-testId={identifier}>{children}</div>;
const divWithoutChildrenMock = (identifier) => <div data-testId={identifier} />;

jest.mock("@chakra-ui/react", () => (
  {
    ...jest.requireActual("@chakra-ui/react"),
    PortalManager: jest.fn(({ children }) => divWithChildrenMock(children, "portal")),
    Modal: jest.fn(({ children }) => divWithChildrenMock(children, "modal")),
    ModalOverlay: jest.fn(({ children }) => divWithChildrenMock(children, "overlay")),
    ModalContent: jest.fn(({ children }) => divWithChildrenMock(children, "content")),
    ModalHeader: jest.fn(({ children }) => divWithChildrenMock(children, "header")),
    ModalFooter: jest.fn(({ children }) => divWithChildrenMock(children, "footer")),
    ModalBody: jest.fn(({ children }) => divWithChildrenMock(children, "body")),
    ModalCloseButton: jest.fn(() => divWithoutChildrenMock("close")),
  }
));

通过查看以下源文件

https://github.com/chakra-ui/chakra-ui/blob/main/packages/modal/src/modal.tsx

您可以看到,即使是模态组件也使用 Portal,因此,您也应该像示例中那样模拟这些组件。

测试 ID 在测试中很有用,可以在快照中检查所有组件是否以正确的顺序呈现。