Test onbeforeunload in Jest
Asked Answered
M

2

10

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.

Manet answered 19/5, 2021 at 6:53 Comment(0)
G
22

You best bet should be dispatching the event yourself.

window.dispatchEvent(new Event("beforeunload"));
Groff answered 13/8, 2021 at 13:21 Comment(1)
If you're testing whether or not the beforeunload event had its default action prevented, by checking its defaultPrevented property, make sure to construct a cancellable event. javascript const event = new Event('beforeunload', { cancelable: true }); window.dispatchEvent(event); Decumbent
E
0

In case anyone needs a React Testing Library solution, the best way would be to have the following unit tests:

  describe('when attempting to leave the app', () => {
    const removeEventListener = window.removeEventListener;
    const mockedRemoveEventListener = jest.fn();

    beforeEach(() => {
      window.removeEventListener = mockedRemoveEventListener;
    });

    afterEach(() => {
      window.removeEventListener = removeEventListener;
    });

    it('should execute your callback when the user attempts to leave the page', () => {
      render(<MyComponent />);

      act(() => {
        fireEvent(window, new Event('beforeunload'));
      });

      expect(callBackToBeTested).toHaveBeenCalledWith('Why?');
    });

    it('should remove the event listener when the component unmounts', () => {
      const { unmount } = render(<MyComponent />);
      unmount();

      expect(mockedRemoveEventListener).toHaveBeenCalledWith('beforeunload', expect.any(Function));
    });
  });
Ey answered 18/10, 2023 at 17:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.