首页 > 解决方案 > 如何使用 Jest 在 Vuejs 应用程序上监视 window.location.assign?

问题描述

我需要为我的单元测试监视 window.location.assign。但是当我运行测试时,我得到了这个错误。

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

这是我的代码:

jest.spyOn(window.location, "assign");

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

标签: unit-testingvuejs2jestjs

解决方案


由于 Jest v25(使用较新版本的 JSDOM),您将收到以下错误:

TypeError: Cannot assign to read only property 'assign' of object '[object Location]'

顺便说一句,这不是 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')
  })
})

推荐阅读