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环境不匹配,因此无法生效
修复步骤
按顺序执行以下操作即可解决问题:
- 卸载当前存在版本冲突的测试依赖
# npm用户执行 npm uninstall @testing-library/react-native @types/react-test-renderer # yarn用户执行 yarn remove @testing-library/react-native @types/react-test-renderer
- 安装和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
- 检查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)" ] }
- 清除Jest缓存后重新运行测试
# 清除缓存 npm test -- --clearCache # 重新执行测试 npm test
注意事项
后续升级测试相关依赖时,必须提前确认版本和当前项目的React、React Native、Expo SDK版本适配关系,不要跨大版本拉取依赖,避免再次出现版本兼容问题。
内容的提问来源于stack exchange,提问作者EI-01
相关产品推荐
相关产品推荐

