reactjs - 如何测试 componentWillUnmount

标签 reactjs jestjs

我在类组件中有以下代码,我正在尝试测试 componentWillUnmount。

export class Hello extends React.PureComponent {
  constructor(){
    super();
    this.isCLoseFromHeaderClicked = true;
  }
  componentWillUnmount() {
    if(this.isCLoseFromHeaderClicked) { this.props.closeModal(); }
  }
 ....do some other stuff...
}

我为它写了如下测试用例

  describe('componentWillUnmount', () => {
    it('componentWillUnmount should be called', () => {
        wrapper = shallowWithIntl(<Hello {...props} />);
        const componentWillUnmount = jest.spyOn(wrapper.instance(), 'componentWillUnmount');
        wrapper.unmount();
        expect(componentWillUnmount).toHaveBeenCalled();
    });
  });

此测试用例通过但覆盖率未达到要求。我还需要测试 else 部分

enter image description here

有谁知道我该如何测试 else 部分?

最佳答案

我会简单地尝试 wrapper.instance().isCloseFrom... = false(在卸载之前)以测试未调用 closeModal

关于reactjs - 如何测试 componentWillUnmount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60582187/

相关文章:

javascript - 如何在 Redux 中不使用 .toYS() 的情况下将 Immutable js 数据结构转换为用例数组?

rxjs - 在 RxJS observable 的 subscribe() 中,Jest 没有处理来自 expect() 的错误

ruby-on-rails - 如何在不使用表单助手的情况下使用 Rails Paperclip 上传图像

javascript - Flow Type高阶组件(HOC)props类型保存

reactjs - React useEffect 包括缺少的依赖项会破坏它

javascript - 开 Jest : how to mock a dependency that listens to events?

typescript - 使用 TypeScript 的 Jest 测试无法识别导入别名

javascript - Jest Enzyme setState of memoryRouter dependent

reactjs - react storybook jest snapshots 导致错误 Cannot find module '../../package' from 'node.js'

javascript - React.js : props. 状态为空白(null)