最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Test onbeforeunload in Jest - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked May 19, 2021 at 6:53 Reshan KumarasingamReshan Kumarasingam 4538 silver badges25 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 22

You best bet should be dispatching the event yourself.

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

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));
    });
  });
发布评论

评论列表(0)

  1. 暂无评论