I have a code which will execute whenever we navigate thro bowser back/forward arrow click event. I need to test this event listener using the react testing library.
const useWindowPop = (switchOrg) => {
useEffect(() => {
window.onpopstate = (e) => {
if (isLoggedIn) {
const queryOrg = queryString.parse(window.location.search);
if (queryOrg?.org) {
switchOrg(queryOrg?.org);
}
}
};
}, []);
};
when I am trying to test this snippet using react-testing library, I am not able to get this event listener executed. I am trying test this like below:
it("fires history event on Window", () => {
const switchOrg = jest.fn();
renderHook(() => useWindowPop(switchOrg), {
wrapper,
});
act(() => {
fireEvent.popState(window);
});
fireEvent(
window,
new window.PopStateEvent("popstate", {
location: "/track?org=123",
state: { page: 1 },
})
);
expect(switchOrg).toHaveBeenCalled();
});
It works fine for me. The
popstateevent is fired correctly.E.g.
useWindowPop.ts:useWindowPop.test.ts:Test result:
package versions: