Unit testing 如何使用Jest在Vuejs应用程序上监视window.location.assign?
我需要spyOn window.location.assign进行单元测试。但是当我运行测试时,我得到了这个错误Unit testing 如何使用Jest在Vuejs应用程序上监视window.location.assign?,unit-testing,vuejs2,jestjs,Unit Testing,Vuejs2,Jestjs,我需要spyOn window.location.assign进行单元测试。但是当我运行测试时,我得到了这个错误 无法监视assign属性,因为它不是函数;而不是给定未定义的 这是我的密码: jest.spyOn(window.location, "assign"); 有人能给我一些关于这个案例的提示或解决方案吗?因为在jest测试和window.location.assign中不能通过global关键字访问,所以您可以尝试 jest .spyOn(global.location, "ass
无法监视assign属性,因为它不是函数;而不是给定未定义的
这是我的密码:
jest.spyOn(window.location, "assign");
有人能给我一些关于这个案例的提示或解决方案吗?因为在jest测试和
window.location.assign中不能通过global
关键字访问,所以您可以尝试
jest
.spyOn(global.location, "assign")
.mockImplementation(url => console.log(url))
由于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')
})
})
在这里,我看到一些人已经应用了同样的东西,感谢FixMate。顺便说一句,我们在Ezyme配置中添加了此解决方案,而不是在相应的单元测试中添加了此解决方案,我认为它应该在相同范围内的任何测试中解决相同的问题。TypeError:无法分配给对象“[object Location]”的只读属性“assign”