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

Expo应用集成react-native-paper后Jest测试失败求助

解决Expo + React Native Paper的Jest测试导入报错问题

问题根源

  1. 版本不匹配:jest-expo@48.0.2与项目使用的expo@47.0.12版本冲突,导致测试环境依赖混乱
  2. 转译白名单缺失:react-native-paper未被加入Jest的transformIgnorePatterns,测试时无法正确转译该库代码
  3. Babel插件环境限制:react-native-paper/babel插件仅在生产环境启用,测试环境缺少必要的代码转换

解决方案

1. 对齐Jest-Expo与Expo版本

修改package.json中的devDependencies,将jest-expo版本调整为与Expo一致的^47.0.0:

"devDependencies": {
  "@babel/core": "^7.12.9",
  "@expo/ngrok": "^4.1.0",
  "@testing-library/jest-native": "^5.4.2",
  "@testing-library/react-native": "^11.5.4",
  "@types/jest": "^29.4.0",
  "jest": "^26.6.3",
  "jest-expo": "^47.0.0"
}

2. 更新Jest转译白名单

在package.json的jest配置中,将react-native-paper添加到transformIgnorePatterns的例外列表:

"jest": {
  "preset": "jest-expo",
  "setupFilesAfterEnv": [
    "@testing-library/jest-native/extend-expect"
  ],
  "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|react-native-paper)"
  ],
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "jsx"
  ]
},

3. 调整Babel插件配置

修改babel.config.js,将react-native-paper/babel插件移至全局启用(确保测试环境也能获得必要的代码转换):

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: ['react-native-paper/babel'],
  };
};

4. 清理缓存并重装依赖

执行以下命令清除缓存、删除旧依赖并重新安装:

yarn cache clean
rm -rf node_modules yarn.lock
yarn install

验证修复

运行测试命令确认问题解决:

yarn test

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 20:42:02