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

React Native运行Jest测试报isBatchingLegacy属性读取错误

React Native单元测试isBatchingLegacy未定义报错修复方案

报错现象

运行React Native单元测试时持续抛出错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'isBatchingLegacy')

测试用例逻辑极简,排查48小时未解决,参考同类问题方案后修复无效,报错截图如下:
报错截图

根因定位

该报错是测试依赖版本和项目React版本不匹配导致:

  • 项目当前使用react@17.0.2、react-native@0.68.2、Expo SDK 45,整套依赖均为React 17适配版本
  • isBatchingLegacy是React 18新增的内部调度API,React 17环境中不存在该属性
  • 安装的@testing-library/react-native@^9.1.0会自动拉取适配React 18的子依赖,运行时调用React 18专属API就会抛出该错误
  • 项目未显式安装和React版本严格对齐的react-test-renderer,进一步加剧了测试环境的渲染异常
  • 此前参考的同类问题解决方案多针对React 18升级场景,和当前React 17的Expo环境不匹配,因此无法生效

修复步骤

按顺序执行以下操作即可解决问题:

  1. 卸载当前存在版本冲突的测试依赖
# npm用户执行
npm uninstall @testing-library/react-native @types/react-test-renderer

# yarn用户执行
yarn remove @testing-library/react-native @types/react-test-renderer
  1. 安装和React 17、Expo 45完全适配的依赖版本,版本号必须严格对应:
# npm用户执行
npm install --save-dev @testing-library/react-native@9.0.0 react-test-renderer@17.0.2 @types/react-test-renderer@17.0.2

# yarn用户执行
yarn add --dev @testing-library/react-native@9.0.0 react-test-renderer@17.0.2 @types/react-test-renderer@17.0.2
  1. 检查Jest配置,确保使用jest-expo预设。如果项目根目录没有独立的jest.config.js文件,直接在package.json中添加以下配置段:
"jest": {
  "preset": "jest-expo",
  "transformIgnorePatterns": [
    "node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)"
  ]
}
  1. 清除Jest缓存后重新运行测试
# 清除缓存
npm test -- --clearCache
# 重新执行测试
npm test

注意事项

后续升级测试相关依赖时,必须提前确认版本和当前项目的React、React Native、Expo SDK版本适配关系,不要跨大版本拉取依赖,避免再次出现版本兼容问题。

内容的提问来源于stack exchange,提问作者EI-01

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 10:48:18