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

降级jest到26.6.0后报ReferenceError: TextEncoder is not defined如何解决

问题原因

Jest 27.x及以上版本默认在测试运行环境中全局注入了TextEncoder、TextDecoderAPI,而你回退到的Jest 26.6.0版本配套的jsdom环境未内置这两个API,因此运行测试时会抛出未定义错误。

解决方案
  • 如果你使用未eject的CRA(create-react-app)项目,直接修改src/setupTests.js(或ts格式的同名文件),在文件顶部添加如下代码:
import { TextEncoder, TextDecoder } from 'util'

global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder
  • 如果你已经eject了CRA,或者是自定义jest配置的项目,除了上面的修改方式外,也可以在jest.config.js中添加setupFiles配置,指定全局注入的文件:
// jest.config.js
module.exports = {
  // 其他原有配置
  setupFiles: ['<rootDir>/src/setupTests.js']
}
  • 如果运行时提示util包找不到,可以先安装对应的polyfill包再执行上面的配置:
    npm install text-encoding --save-dev
    修改setupTests中的代码为:
import { TextEncoder, TextDecoder } from 'text-encoding'

global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder

相关截图

报错截图
项目结构截图

内容的提问来源于stack exchange,提问作者Wen Li

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:24:03