javascriptreactjsunit-testingjestjs

Check if window.location.reload is invoked in JEST


const ErrorSnackbar = () => {

     const handelePrimaryBtnClick = () => { window.location.reload() }

     return ( <div className = 'sample_class' onClick={handelePrimaryBtnClick}> Sample Code </div> )
}

In jest How to check if window.location.reload() is invoked when I click on the div.


Solution

  • You can spy the reload method and simulate a click on the div, something like:

    it("should reload the page", () => {
      jest.spyOn(window.location, 'reload');
      const component = mount(ErrorSnackbar());
      component.find('.sample_class').simulate('click');
      expect(window.location.reload).toHaveBeenCalled();
    });