测试时如何触发功能组件的卸载?

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)


sli*_*wp2 4

根据这个问题,我们知道shallowrender不支持useEffecthook。我们需要手动使用mount和调用.unmount()方法。

\n

例如

\n

index.tsx

\n
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};\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.tsx

\n
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});\n
Run 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\n
Run Code Online (Sandbox Code Playgroud)\n

软件包版本:

\n
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};\n
Run Code Online (Sandbox Code Playgroud)\n