You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 07:35:03