如何在 React 中使用 Jest 模拟 window.location.href?

2024-05-10

我正在测试不应该在本地运行并且需要模拟的功能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的相关问题 https://stackoverflow.com/questions/54021037/how-to-mock-window-location-href-with-jest-vuejs/63382670但我不清楚这些解决方案是否也适用于 React(有些解决方案不起作用)。


我最终在 React 16 和 Jest 24 上得到了以下结果。

describe("usePageTracking", () => {
  let location;
  const mockLocation = new URL("https://example.com");

  beforeEach(() => {
    location = window.location;
    mockLocation.replace = jest.fn();
    // You might need to mock other functions as well
    // location.assign = jest.fn();
    // location.reload = jest.fn();
    delete window.location;
    window.location = mockLocation;
  });

  afterEach(() => {
    window.location = location;
  });

  // ...
});

也可以看看:

  • https://github.com/facebook/jest/issues/890 https://github.com/facebook/jest/issues/890
  • https://github.com/facebook/jest/issues/5124 https://github.com/facebook/jest/issues/5124
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 React 中使用 Jest 模拟 window.location.href? 的相关文章

随机推荐