所以基本上我有一个 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 它也不起作用。任何帮助表示赞赏。谢谢。
您最好的选择应该是自己调度事件。
window.dispatchEvent(new Event("beforeunload"));
如果有人需要 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));
});
});