如何用 Jest + Vuejs 模拟 window.location.href?

How to mock window.location.href with Jest + Vuejs?

目前,我正在为我的项目实施单元测试,并且有一个包含 window.location.href.

的文件

我想模拟这个来测试,这是我的示例代码:

it("method A should work correctly", () => {
      const url = "http://dummy.com";
      Object.defineProperty(window.location, "href", {
        value: url,
        writable: true
      });
      const data = {
        id: "123",
        name: null
      };
      window.location.href = url;
      wrapper.vm.methodA(data);
      expect(window.location.href).toEqual(url);
    });

但是我得到这个错误:

TypeError: Cannot redefine property: href
        at Function.defineProperty (<anonymous>)

我尝试了一些解决方案但没有解决。我需要一些提示来帮助我摆脱这个麻烦。请帮助。

你可以试试:

global.window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, 'location', {
  value: {
    href: url
  }
});
expect(window.location.href).toEqual(url);  

查看该问题的 Jest Issue:
Jest Issue

我通过添加 writable: true 并将其移至 beforeEach

解决了这个问题

这是我的示例代码:

global.window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, "location", {
    value: {
       href: url
    },
    writable: true
});

可以通过在每次测试中删除这个全局来重写window.location。

delete global.window.location;
const href = 'http://localhost:3000';
global.window.location = { href };

2019 年解决方案from GitHub

delete global.window.location;
global.window = Object.create(window);
global.window.location = {
  port: '123',
  protocol: 'http:',
  hostname: 'localhost',
};

最好的方法可能是创建一个新的 URL 实例,以便它像 location.href 那样解析您的字符串,因此它会更新 location 的所有属性,例如 .hash.search.protocol

it("method A should work correctly", () => {
  const url = "http://dummy.com/";
  Object.defineProperty(window, "location", {
    value: new URL(url)
  } );

  window.location.href = url;
  expect(window.location.href).toEqual(url);

  window.location.href += "#bar"
  expect(window.location.hash).toEqual("#bar");
});

https://repl.it/repls/VoluminousHauntingFunctions

提供的许多示例并未模拟原始 Location 对象的属性。

我所做的只是将 Location 对象 (window.location) 替换为 URL,因为 URL 包含与 "href"、[=20 等 Location 对象相同的属性=], "hash", "host".

Setter 和 Getters 的工作方式也与 Location 对象完全相同。

示例:

const realLocation = window.location;

describe('My test', () => {

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

    test('My test func', () => {

        // @ts-ignore
        delete window.location;

        // @ts-ignore
        window.location = new URL('http://google.com');

        console.log(window.location.href);

        // ...
    });
});

2020 更新


基本

URL object has a lot of the same functionality as the Location object。换句话说,它包括pathnamesearchhostname等属性。因此对于大多数情况,您可以执行以下操作:

delete window.location
window.location = new URL('https://www.example.com')

高级

您还可以模拟您可能需要的 Location methods,它在 URL 界面上不存在:

const location = new URL('https://www.example.com')
location.assign = jest.fn()
location.replace = jest.fn()
location.reload = jest.fn()

delete window.location
window.location = location

基于上面和其他线程中的示例,这里是一个使用 jest 的具体示例,可能会对某人有所帮助:

describe('Location tests', () => {
    const originalLocation = window.location;

    const mockWindowLocation = (newLocation) => {
        delete window.location;
        window.location = newLocation;
    };

    const setLocation = (path) =>
        mockWindowLocation(
            new URL(`https://example.com${path}`)
        );

    afterEach(() => {
        // Restore window.location to not destroy other tests
        mockWindowLocation(originalLocation);
    });

    it('should mock window.location successfully', () => {
        setLocation('/private-path');

        expect(window.location.href).toEqual(
            `https://example.com/private-path`
        );
    });
});

扩展@jabacchetta 的解决方案以避免此设置渗入其他测试:

describe("Example", () => {
  let location;

  beforeEach(() => {
    const url = "https://example.com";
    location = window.location;
    const mockLocation = new URL(url);
    mockLocation.replace = jest.fn();
    delete window.location;
    window.location = mockLocation;
  });

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

你可以试试帮手:

const setURL = url => global.jsdom.reconfigure({url});

describe('Test current location', () => {
  test('with GET parameter', () => {
    setURL('https://test.com?foo=bar');
    // ...your test here
  });
});

这对 Jest + TypeScript + Next.js 有效(如果你使用 useRoute().push

const oldWindowLocation = window.location;

beforeAll(() => {
  delete window.location;
  window.location = { ...oldWindowLocation, assign: jest.fn() };
});

afterAll(() => {
  window.location = oldWindowLocation;
});

2020 年 @testing-library/react 的 window.location.assign 工作示例:

  afterEach(cleanup)
  beforeEach(() => {
    Object.defineProperty(window, 'location', {
      writable: true,
      value: { assign: jest.fn() }
    })
  })

JSDOM 版本

另一种方法,使用 JSDOM,它将提供 window.location.hrefwindow.location 的所有其他属性(例如 window.location.search 以获取查询字符串参数)。

import { JSDOM } from 'jsdom';

...

const { window } = new JSDOM('', {
    url: 'https://localhost/?testParam=true'
});
delete global.window;
global.window = Object.create(window);

可能无关紧要。但是对于那些寻求 window.open('url', attribute) 解决方案的人,我在上面的一些评论的帮助下应用了这个:

window = Object.create(window);
const url = 'https://www.9gag.com';
Object.defineProperty(window, 'open', { value: url });

expect(window.open).toEqual(url);

如何在您的代码库中重新分配 window.location;我们为 Jest 测试找到的最简单的工作设置:

const realLocation = window.location;

beforeEach(() => {
  delete window.location;
});

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

你可以试试jest-location-mock.

npm install --save-dev jest-location-mock

更新 jest 配置 jest.config.js 文件或 jest prop inside package.json:

setupFilesAfterEnv: [ "./config/jest-setup.js" ]

创建jest-setup.js

import "jest-location-mock";

用法:

it("should call assign with a relative url", () => {
    window.location.assign("/relative-url");
    expect(window.location).not.toBeAt("/");
    expect(window.location).toBeAt("/relative-url");
});