在Jest中进行卸载前测试

k7fdbhmy  于 2023-11-15  发布在  Jest
关注(0)|答案(2)|浏览(138)

所以基本上我有一个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?";
    };
  }, []);

字符串
我试着在jest中测试它,但是return语句从来没有执行过。我的测试如下

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


即使我嘲笑onBeforeUnload,它也不起作用。任何帮助都是感激的。谢谢。

z0qdvdin

z0qdvdin1#

你最好还是自己去处理这个事件。

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

字符串

yqyhoc1h

yqyhoc1h2#

如果有人需要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));
    });
  });

字符串

相关问题