如何使用 Jest 监视 Vuejs 应用程序上的 window.location.assign?

Hoa*_*Son 8 unit-testing jestjs vuejs2

我需要对 window.location.assign 进行单元测试。但是当我运行测试时,我收到此错误。

Cannot spy the assign property because it is not a function; undefined given instead

这是我的代码:

jest.spyOn(window.location, "assign");
Run Code Online (Sandbox Code Playgroud)

有人能给我一些关于这个案例的提示或解决方案吗?

Kev*_*inH 5

从 Jest v25(使用更新版本的 JSDOM)开始,您将收到以下错误:

TypeError: Cannot assign to read only property 'assign' of object '[object Location]'
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这不是 Jest/JSDOM 错误。这是正常的浏览器行为,JSDOM 尝试像真正的浏览器一样运行。

一种解决方法是删除位置对象,创建您自己的位置对象,并在运行测试后将其重置为原始位置对象:

describe('My awesome unit test', () => {
  // we need to save the original object for later to not affect tests from other files
  const realLocation = global.location

  beforeAll(() => {
    delete global.location
    global.location = { assign: jest.fn() }
    // or even like this if you are also using other location properties (or if TypeScript complains):
    // global.location = { ...realLocation, assign: jest.fn() }
  })

  afterAll(() => {
    global.location = realLocation
  })

  it('should call location.assign', () => {    
    // ...your test code

    expect(global.location.assign).toHaveBeenCalled()

    // or even better:
    // expect(global.location.assign).toHaveBeenCalledWith('/my_link')
  })
})
Run Code Online (Sandbox Code Playgroud)


And*_*rle -1

由于jest测试中window只能通过关键字访问, jsdom中没有实现,你可以尝试globalwindow.location.assign

jest
 .spyOn(global.location, "assign")
 .mockImplementation(url => console.log(url))
Run Code Online (Sandbox Code Playgroud)

  • 类型错误:无法分配给对象“[对象位置]”的只读属性“分配” (3认同)