在 Jest 中测试 onbeforeunload
Test onbeforeunload in Jest
所以基本上我有一个 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"));
所以基本上我有一个 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"));