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

React Native 0.61.5配置Jest运行时报error-guard.js缺分号SyntaxError

报错根因

该报错是React Native 0.61版本内置的Flow类型语法未被Babel转译导致:Jest默认不处理node_modules下的依赖代码,当前配置存在两处问题:

  • 使用.babelrc作为Babel配置文件,该格式为局部配置,默认仅作用于项目源码目录,无法处理node_modules下的react-native依赖代码
  • transformIgnorePatterns规则不适配0.61版本的React Native包结构,转译范围未正确覆盖需要处理的依赖

可行解决方案

步骤1:替换Babel配置文件

删除原有的.babelrc文件,在项目根目录新建babel.config.js,写入以下内容:

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

babel.config.js是Babel的全局配置文件,可作用于node_modules下的依赖代码。

步骤2:修改jest.config.js配置

调整transformIgnorePatterns规则,适配0.61版本的包结构:

module.exports = {
  preset: 'react-native',
  transformIgnorePatterns: [
    'node_modules/(?!(react-native|@react-native-community)/)'
  ]
};

步骤3:安装缺失依赖

确认已安装所有测试所需依赖,缺失的话执行以下命令安装:

npm install --save-dev metro-react-native-babel-preset @babel/core @babel/runtime babel-jest jest react-test-renderer

配置完成后重新运行Jest即可正常执行测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:36:00