我需要spyOn window.location.assign进行单元测试。但是,当我运行测试时,出现此错误。
Cannot spy the assign property because it is not a function; undefined given instead
这是我的代码:
jest.spyOn(window.location, "assign");
有人可以给我一些有关此案的提示或解决方案吗?
答案 0 :(得分:1)
由于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')
})
})
答案 1 :(得分:0)
由于在玩笑测试中只能通过window
关键字访问global
,而在jsdom中没有实现window.location.assign
,因此可以尝试
jest
.spyOn(global.location, "assign")
.mockImplementation(url => console.log(url))