
MSW 升级至 2.0+ 后默认仅支持 Node.js 原生 fetch,而 Jest 默认使用 jsdom 环境(依赖 whatwg-fetch 等 polyfill),导致请求无法被拦截。需替换全局 fetch 实现为 Node 兼容版本并补全 Web 标准 API。
msw 升级至 2.0+ 后默认仅支持 node.js 原生 `fetch`,而 jest 默认使用 jsdom 环境(依赖 `whatwg-fetch` 等 polyfill),导致请求无法被拦截。需替换全局 fetch 实现为 node 兼容版本并补全 web 标准 api。
MSW 2.0 是一次架构级重构,其核心设计目标是深度集成 Node.js 运行时能力(如 undici、node:util),因此主动放弃了对浏览器 polyfill(如 whatwg-fetch、isomorphic-fetch)的兼容性。当你在 Jest 中沿用旧版配置(尤其是基于 jsdom 的测试环境),即使正确注册了 http.get() 处理器,实际发出的请求仍由 jsdom 内置的不兼容 fetch 实现执行,MSW 无法劫持——最终抛出 TypeError: Failed to fetch(状态码 0)正是这一失配的典型表现。
要使 MSW 2.0+ 在 Jest 中正常工作,关键在于统一运行时 fetch 实现:移除所有第三方 fetch polyfill,并将 global.fetch 替换为 Node 原生兼容的 undici.fetch,同时注入 TextEncoder、TextDecoder、Blob、FormData 等缺失的全局 Web API。
✅ 正确配置步骤
-
卸载旧版 polyfill(如 whatwg-fetch):
npm uninstall whatwg-fetch # 或 yarn remove whatwg-fetch
-
创建 jest.polyfills.js 文件(推荐存放于项目根目录):
// jest.polyfills.js const { TextEncoder, TextDecoder } = require('node:util'); const { Blob } = require('node:buffer'); const { fetch, Request, Response, Headers, FormData } = require('undici'); // 注入全局 Web 标准 API globalThis.TextEncoder = TextEncoder; globalThis.TextDecoder = TextDecoder; globalThis.Blob = Blob; globalThis.fetch = fetch; globalThis.Request = Request; globalThis.Response = Response; globalThis.Headers = Headers; globalThis.FormData = FormData; -
在 jest.config.js 中启用该 polyfill:
module.exports = { setupFiles: ['./jest.polyfills.js'], // 若已存在 setupFiles,请将其合并到数组中 // 其他配置保持不变... }; -
验证 MSW 配置(确保使用 http 模块而非 rest):
// setupTests.ts 或 test setup 文件 import { setupServer } from 'msw/node'; import { http } from 'msw'; const server = setupServer( http.get('http://localhost:1800/users_info', () => { return HttpResponse.json({ userId: 123 }); }) ); beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close());
⚠️ 注意事项
- 不要混用 rest 和 http 模块:MSW 2.0+ 已废弃 rest 模块,必须使用 http。
- undici 版本需匹配:确保安装 undici@^5.27.0 或更高版本(MSW 2.x 官方要求)。
- Jest 环境必须为 jsdom:若使用 node 环境,无需此配置,但多数前端测试场景依赖 jsdom。
- 避免重复 polyfill:检查 setupFilesAfterEnv 或测试文件中是否手动调用了 fetch 初始化逻辑,应全部移除。
完成上述配置后,MSW 2.0+ 将能正确拦截 Jest 中发起的 fetch 请求,HttpResponse.json() 响应也将被准确返回。这不仅是兼容性修复,更是向标准化 Node 测试环境迈出的关键一步。

















