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

Jest执行React Native库单元测试时遇Unexpected identifier 'ErrorHandler'错误

解决Jest测试中"Unexpected identifier: 'ErrorHandler'"错误

问题根源

错误出在@react-native/js-polyfills包内的TypeScript类型定义语法(type ErrorHandler = ...)未被Jest转译。Jest默认会忽略node_modules目录下的文件转译,但这个包包含未编译的TS代码,必须手动将其加入转译白名单。

修复步骤

1. 更新Jest的转译忽略规则

修改package.json中的jest配置,把@react-native/js-polyfills加入transformIgnorePatterns的白名单,让Babel处理该包的代码:

"jest": {
  "preset": "react-native",
  "transformIgnorePatterns": [
    "/node_modules/(?!react-native|@react-native-svg|react-native-svg|@react-native/js-polyfills)"
  ]
}

2. 确保Babel配置正确(若未配置则创建)

项目根目录新建或修改babel.config.js,使用React Native官方的metro Babel预设,配合TypeScript预设:

module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    '@babel/preset-typescript'
  ],
};

这个预设能正确处理React Native及TypeScript代码的转译,确保Jest能解析所有依赖中的语法。

3. 验证测试命令

你的测试命令已经启用了ESM支持,保持现有配置即可:

"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"

额外检查

  • 确认tsconfig.json中的编译配置正常,lib目录已正确生成编译后的JS代码
  • 若仍有ESM相关问题,可在Jest配置中添加:
"extensionsToTreatAsEsm": [".ts", ".tsx"],
"moduleNameMapper": {
  "^(\\.{1,2}/.*)\\.js$": "$1"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 06:32:05