I'm testing functionality that is not supposed to run locally and need to mock window.location.href
:
const usePageTracking = (): void => {
const location = useLocation();
useEffect(() => {
if (!window.location.href.includes("localhost")) {
ReactGA.initialize("UA-000000-01");
ReactGA.pageview(window.location.pathname + window.location.search);
}
}, []);
};
In my tests:
describe("usePageTracking", () => {
it("initializes ReactGA", () => {
render(<Example />);
expect(ReactGA.initialize).toHaveBeenCalled();
});
it("tracks page view", () => {
render(<Example />);
expect(ReactGA.pageview).toHaveBeenCalledWith("/");
});
});
Note: there's a related question around Vue but it wasn't clear to me if the solutions apply to React as well (some just didn't work).