Reactjs 如何测试组件卸载

Reactjs 如何测试组件卸载,reactjs,jestjs,Reactjs,Jestjs,我在一个类组件中有以下代码,我正在尝试测试该组件是否会卸载 export class Hello extends React.PureComponent { constructor(){ super(); this.isCLoseFromHeaderClicked = true; } componentWillUnmount() { if(this.isCLoseFromHeaderClicked) { this.props.closeModal(); }

我在一个类组件中有以下代码,我正在尝试测试该组件是否会卸载

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();
    });
  });
description('componentWillUnmount',()=>{
它('应调用componentWillUnmount',()=>{
wrapper=shallowWithIntl();
const componentWillUnmount=jest.spyOn(wrapper.instance(),'componentWillUnmount');
wrapper.unmount();
expect(componentWillUnmount).tohavebeincall();
});
});
此测试用例通过,但覆盖率未达到要求。我还需要测试其他部分


有人知道如何测试else部分吗?

我只想试试
wrapper.instance().isCloseFrom…=false
(卸载前)以测试
closeModal
是否未调用

,但您没有
else
部件。您应该测试当
isCloseFromHeaderClicked
为true时是否调用closeModal。(测试1)。测试2,当
从headerclicked关闭时不调用它是错误的谢谢@grodzi是的,你是对的,但我找不到这样的例子。你能给我举个例子,如何设置isCloseFromHeaderClicked的值吗?我没有环境测试(也没有勇气)。我只想尝试
wrapper.instance().isCloseFrom…=false
(卸载前)非常感谢@grodzi。成功了。如果你只是添加了相同的评论,那么我会将其标记为一个答案:)很高兴能够帮助@User7354632781:)