【问题标题】:How to trigger unmounting of functional components while testing?测试时如何触发功能组件的卸载?
【发布时间】:2021-07-26 18:17:46
【问题描述】:

我使用“useEffect”在功能组件中实现“componentWillUnmount”的功能。使用 Jest/Enzyme 测试组件时如何触发?

我的组件:

const myComp = () => {
  useEffect(() => () => {
    console.log('Unmounted');
  }, []);
  return <div>Test</div>;
}

【问题讨论】:

  • @slideshowp2,感谢您的回复。您可能没有注意到我将 console.log 放在了返回函数中,而不是在回调中。或者你能告诉我正确的方法吗...?

标签: reactjs jestjs react-hooks enzyme


【解决方案1】:

根据这个issue,我们知道shallow 渲染不支持useEffect 钩子。我们需要使用mount并手动调用.unmount()方法。

例如

index.tsx:

import React, { useEffect } from 'react';

export const MyComp = () => {
  useEffect(
    () => () => {
      console.log('Unmounted');
    },
    []
  );
  return <div>Test</div>;
};

index.test.tsx:

import React from 'react';
import { mount } from 'enzyme';
import { MyComp } from './';

describe('67384129', () => {
  it('should pass', () => {
    const wrapper = mount(<MyComp />);
    wrapper.unmount();
  });
});

测试结果:

 PASS  examples/67384129/index.test.tsx (8.233 s)
  67384129
    ✓ should pass (53 ms)

  console.log
    Unmounted

      at examples/67384129/index.tsx:6:15

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.121 s

软件包版本:

"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0"
"jest": "^26.6.3",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",

【讨论】:

  • 这就是我要找的。包装器.卸载。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-12-23
  • 2020-03-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多