我拼命地試圖測驗一個模態,但無法理解它!
這是我所在的位置:
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 知道在哪里放置模態但快照始終為空。
uj5u.com熱心網友回復:
嗯,一個選項可能是模擬PortalManager自己并使它像 aReact.Component而不是 a 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 在測驗中很有用,可以在快照中檢查所有組件是否以正確的順序呈現。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/328592.html
下一篇:在一個嵌套回圈中更新字典
