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.
beforeunload
event had its default action prevented, by checking itsdefaultPrevented
property, make sure to construct a cancellable event.javascript const event = new Event('beforeunload', { cancelable: true }); window.dispatchEvent(event);
– Decumbent