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

React Native TS项目Jest测试遇unexpected token error问题求助

解决React Native TypeScript项目中Jest导入@react-navigation/native-stack时的Unexpected Token错误

问题原因

Jest默认不会转译node_modules目录下的包,但@react-navigation/native-stack这类库可能使用了未转译的ES语法,导致Jest无法解析,抛出「Unexpected Token」错误。

解决方案

1. 调整Jest配置,让Jest转译导航相关包

在项目根目录的jest.config.js(或package.json的jest字段)中,修改transformIgnorePatterns,将@react-navigation及相关React Native生态包排除在忽略列表外:

module.exports = {
  preset: 'react-native',
  transformIgnorePatterns: [
    'node_modules/(?!(@react-navigation|react-native|@react-native-community|@react-native-picker)/)',
  ],
  // 保留其他已有配置
};

通过负向正则断言,告诉Jest不要忽略这些需要转译的第三方包。

2. 确保Babel配置正确

检查babel.config.js,确保包含React Native的metro预设,若使用TypeScript需添加TypeScript预设:

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

如果项目用到可选链、空值合并等ES新语法,可额外添加对应Babel插件(metro预设通常已包含,若仍有问题再补充):

module.exports = {
  presets: ['module:metro-react-native-babel-preset', '@babel/preset-typescript'],
  plugins: [
    '@babel/plugin-proposal-optional-chaining',
    '@babel/plugin-proposal-nullish-coalescing-operator',
  ],
};

3. 安装必要依赖

确保项目已安装Jest和Babel相关的必要依赖,版本需与React Native兼容:

# 使用npm
npm install --save-dev @babel/core babel-jest @babel/preset-typescript

# 使用yarn
yarn add --dev @babel/core babel-jest @babel/preset-typescript

4. 适配TypeScript的ES模块导入

如果项目使用ES模块语法而非CommonJS,在jest.config.js中添加以下配置,让Jest正确解析TypeScript文件:

module.exports = {
  // 保留其他配置
  extensionsToTreatAsEsm: ['.ts', '.tsx'],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
};

5. 清除缓存并重新运行测试

修改配置后,清除Jest缓存再执行测试,避免缓存导致的问题:

npx jest --clearCache
npx jest

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 00:43:18