我拼命尝试测试一个模态,但无法理解它!
这就是我现在的位置:
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 在测试中非常有用,可以在快照中检查所有组件是否以正确的顺序呈现。
关于reactjs - 有没有办法用react-test-renderer测试Chakra-ui模式对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69585390/