我正在测试不应在本地运行的功能,并需要模拟 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);
}
}, []);
};
在我的测试中:
describe("usePageTracking", () => {
it("initializes ReactGA", () => {
render(<Example />);
expect(ReactGA.initialize).toHaveBeenCalled();
});
it("tracks page view", () => {
render(<Example />);
expect(ReactGA.pageview).toHaveBeenCalledWith("/");
});
});
注意:有一个关于Vue的相关问题,但我不确定解决方案是否也适用于React(有些解决方案不起作用)。