使用Jest与MSW进行React前端测试时遭遇TextEncoder未定义错误
Jest + MSW测试React组件时触发
ReferenceError: TextEncoder is not defined的解决方法 问题描述
使用Jest和MSW进行React前端测试,尝试通过原生fetch从Mock API获取数据到组件,却出现ReferenceError: TextEncoder is not defined错误。
代码示例
handlers.ts
// /mocks/handlers.ts import { http, HttpResponse } from "msw"; export const handlers = [ http.get("https://localhost:4000/1/messages", () => { return HttpResponse.json({ _id: "1", name: "John Doe", message: "Hello world!" }) }) ]
server.ts(报错文件)
// /mocks/server.ts import { setupServer } from 'msw/node' import { handlers } from './handlers' export const server = setupServer(...handlers)
setupTests.ts
import "@testing-library/jest-dom"; import { server } from "./mocks/server"; beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close())
component.tsx
useEffect(() => { fetch("https://localhost:4000/1/messages") .then(res => res.json()) .then(data => setChatheads(data)) .catch(() => setError("Error fetching messages")); }, [])
已尝试方案
曾添加以下代码但未解决问题:
import { TextEncoder, TextDecoder } from 'util'; Object.assign(global, { TextDecoder, TextEncoder });
也手动修改过node_modules/whatwg_url/dist/encoding.js添加类似代码,错误依旧。
版本信息
- Jest 29.7.0
- TypeScript 5.6.2
- MSW 2.4.9
期望结果
修改相关配置后,Mock API可正常工作,请求https://localhost:4000/1/messages能返回指定对象:
{ "_id": "1", "name": "John Doe", "message": "Hello world!" }
解决方案
方法1:提前在setupTests.ts中注入全局API
将TextEncoder/TextDecoder的全局注入代码移到setupTests.ts最顶部,确保在MSW初始化前执行:
// 先注入全局API import { TextEncoder, TextDecoder } from 'util'; Object.assign(global, { TextDecoder, TextEncoder }); import "@testing-library/jest-dom"; import { server } from "./mocks/server"; beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close())
方法2:通过Jest配置文件配置全局初始化
- 创建
src/mocks/globals.ts文件:
import { TextEncoder, TextDecoder } from 'util'; global.TextEncoder = TextEncoder; global.TextDecoder = TextDecoder;
- 修改
jest.config.js(或jest.config.ts),添加setupFiles配置:
module.exports = { // 其他已有配置... setupFiles: ['<rootDir>/src/mocks/globals.ts'], setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'], };
方法3:安装whatwg-url polyfill
如果上述方法无效,安装依赖并在setup文件中导入:
npm install whatwg-url --save-dev
在setupTests.ts顶部添加:
import 'whatwg-url';
原因说明
Jest 29默认的jsdom测试环境未内置TextEncoder/TextDecoder API,而MSW内部依赖这些API处理请求,因此需要手动全局注入或引入polyfill。之前尝试无效的原因大概率是注入时机太晚,在MSW初始化之后才执行,导致API未被正确挂载。
内容的提问来源于stack exchange,提问作者user22362540
相关产品推荐
相关产品推荐

