我正在测试不应该在本地运行并且需要模拟的功能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(有些只是不起作用)。