在 Jest 中卸载之前进行测试

问题描述 投票:0回答:2

所以基本上我有一个 onbeforeunload 函数来照顾并警告用户是否决定重新加载或关闭选项卡。我的代码如下

  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?";
    };
  }, []);

我试图开玩笑地测试它,但 return 语句从未被执行。我的测试如下

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

即使我嘲笑 onBeforeunload 它也不起作用。任何帮助表示赞赏。谢谢。

javascript reactjs unit-testing jestjs gatsby
2个回答
21
投票

您最好的选择应该是自己调度事件。

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

0
投票

如果有人需要 React 测试库解决方案,最好的方法是进行以下单元测试:

  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));
    });
  });
© www.soinside.com 2019 - 2024. All rights reserved.