Jest测试报错:无法为global的只读属性fetch赋值
解决方案:Jest spyOn global.fetch 报错 "Cannot assign to read only property 'fetch'"
问题原因
Node.js 20+ 版本中,global.fetch 被设置为只读属性,而 Jest 的 jest.spyOn 方法默认会尝试修改目标属性的可写性来完成 spy 操作,因此触发了只读属性赋值的错误。
可行解决方案
1. 给 spyOn 添加 writable: true 参数
在调用 jest.spyOn 时显式指定属性可写,覆盖默认行为:
const spyOnFetch = jest.spyOn(global, 'fetch', { writable: true });
测试完成后记得恢复原方法:
afterEach(() => { spyOnFetch.mockRestore(); });
或者在测试文件末尾统一恢复所有 mock:
afterAll(() => { jest.restoreAllMocks(); });
2. 手动替换并恢复 fetch
绕过 jest.spyOn,直接手动替换 global.fetch,测试结束后恢复原实现:
// 保存原始 fetch 方法 const originalFetch = global.fetch; beforeAll(() => { // 替换为 jest mock 函数 global.fetch = jest.fn(); }); afterAll(() => { // 恢复原始 fetch 方法 global.fetch = originalFetch; });
3. 检查 Jest 测试环境配置
如果是前端项目,确保 Jest 使用 jsdom 环境(而非默认的 node 环境),jsdom 中的 fetch 并非只读属性:
在 jest.config.js 或 jest.config.ts 中设置:
module.exports = { testEnvironment: 'jsdom', // 其他配置... };
4. 降级 Node.js 版本(临时方案)
如果上述方法都无法快速生效,可以临时降级到 Node.js 18.x 版本(该版本中 global.fetch 仍为可写属性),但不推荐长期使用。
内容的提问来源于stack exchange,提问作者Exiosys
相关产品推荐
相关产品推荐

