how to test componentWillUnmount

Viewed 617

I have following code in a class component and I am trying to test the componentWillUnmount.

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

I wrote test case for it as follows

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

This test case passes but coverage is not meeting. I also need to test the else part

enter image description here

Does anyone know how can i test the else part?

1 Answers

I would simply try wrapper.instance().isCloseFrom... = false (before unmounting) in order to test that closeModal is not called

Related