Search code examples
javascriptreactjsunit-testingjestjsgatsby

Test onbeforeunload in Jest


So basically I have a onbeforeunload function taking care and warning users if they decided to reload or close the tab. My code is as below

  useEffect(() => {
   
    //this will prevent users from accidently refreshing / closing tab
    window.onbeforeunload = () => {
      return "Are you sure you want to do this yada yada yada yada?";
    };
  }, []);

I tried to test it in jest but the return statement is never executed. my test as below

window.location.reload();
expect(window.onbeforeunload).toHaveBeenCalled();

even if I mock the onBeforeunload it doesn't work. Any help is apreciated. Thanks.


Solution

  • You best bet should be dispatching the event yourself.

    window.dispatchEvent(new Event("beforeunload"));