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.
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.
Share Improve this question asked May 19, 2021 at 6:53 Reshan KumarasingamReshan Kumarasingam 4538 silver badges25 bronze badges2 Answers
Reset to default 22You best bet should be dispatching the event yourself.
window.dispatchEvent(new Event("beforeunload"));
In case anyone needs a React Testing Library solution, the best way would be to have the following unit tests:
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));
});
});