unit-testing - 如何使用 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");
谁能给我一些关于这个案例的提示或解决方案?
解决方案
由于 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')
})
})
推荐阅读
- python-3.x - 如何读取 Windows 注册表文件以检查值?[Python]
- javascript - 相反,计数器返回 0,我的代码返回错误
- eclipse-plugin - 在 Eclipse 中找不到 ContextFactory
- javascript - 如何修复 MaxListenersExceededWarning 错误?
- android - 我们可以使用 WorkManager 在其他 UniqueWork 的队列中添加另一个 UniqueWork
- javascript - 如何在悬停在 anchorEl 和“popover”上时继续显示“popover”?
- angular7 - 如何防止 ngAfterViewInit() 在 ngOninit 完成执行之前被调用
- python - 将自定义图例(标记颜色)添加到 plotly python
- sass - SASS如何获取列表的第n个值和键?
- google-cloud-platform - 如何在 Google Cloud Storage 上创建和写入 XLSX 文件