Pav*_*sha 6 reactjs jestjs enzyme react-hooks
我使用“useEffect”来实现功能组件中“componentWillUnmount”的功能。如何在使用 Jest/Enzyme 测试组件时触发它?
我的组件:
const myComp = () => {
useEffect(() => () => {
console.log('Unmounted');
}, []);
return <div>Test</div>;
}
Run Code Online (Sandbox Code Playgroud)
小智 13
如果您使用的是react-testing-library,那么:
const { unmount } = render(<Component />);
unmount();Run Code Online (Sandbox Code Playgroud)
根据这个问题,我们知道shallowrender不支持useEffecthook。我们需要手动使用mount和调用.unmount()方法。
例如
\nindex.tsx:
import React, { useEffect } from \'react\';\n\nexport const MyComp = () => {\n useEffect(\n () => () => {\n console.log(\'Unmounted\');\n },\n []\n );\n return <div>Test</div>;\n};\nRun Code Online (Sandbox Code Playgroud)\nindex.test.tsx:
import React from \'react\';\nimport { mount } from \'enzyme\';\nimport { MyComp } from \'./\';\n\ndescribe(\'67384129\', () => {\n it(\'should pass\', () => {\n const wrapper = mount(<MyComp />);\n wrapper.unmount();\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n测试结果:
\n PASS examples/67384129/index.test.tsx (8.233 s)\n 67384129\n \xe2\x9c\x93 should pass (53 ms)\n\n console.log\n Unmounted\n\n at examples/67384129/index.tsx:6:15\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 9.121 s\nRun Code Online (Sandbox Code Playgroud)\n软件包版本:
\nimport React, { useEffect } from \'react\';\n\nexport const MyComp = () => {\n useEffect(\n () => () => {\n console.log(\'Unmounted\');\n },\n []\n );\n return <div>Test</div>;\n};\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
15550 次 |
| 最近记录: |