【发布时间】:2020-12-04 03:32:15
【问题描述】:
我正在测试不应该在本地运行并且需要模拟 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("/");
});
});
注意:有一个 related question around Vue,但我不清楚这些解决方案是否也适用于 React(有些只是不起作用)。
【问题讨论】:
标签: reactjs testing jestjs react-hooks mocking