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

8

我正在测试不应在本地运行的功能,并需要模拟 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(有些解决方案不起作用)。
2个回答

10

我最后使用的是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;
  });

  // ...
});

另请参阅:


9

使用 Object.defineProperty() 来定义 window.location 的 getter。

例如:

usePageTracking.ts

import { useEffect } from 'react';

export const usePageTracking = (): void => {
  useEffect(() => {
    console.log(window.location.href);
  }, []);
};

Example.tsx:

import React from 'react';
import { usePageTracking } from './usePageTracking';

export function Example() {
  usePageTracking();
  return <div>example</div>;
}

Example.test.tsx:

import React from 'react';
import { Example } from './Example';
import { render } from '@testing-library/react';

describe('Example', () => {
  it('should pass', () => {
    Object.defineProperty(window, 'location', {
      get() {
        return { href: 'stackoverflow.com' };
      },
    });
    render(<Example />);
  });
});

测试结果

 PASS  examples/63409476/Example.test.tsx (11.048 s)
  Example
    ✓ should pass (39 ms)

  console.log
    stackoverflow.com

      at examples/63409476/usePageTracking.ts:5:13

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.768 s

软件包版本:

"jest": "^26.6.3",
"ts-jest": "^26.4.4",

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
}

1
Object.defineProperty() 在 TypeScript 中完美运作! - scottwernervt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接