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

使用Jest和React Native Testing Library组件测试时render方法报错

问题:使用render方法测试组件时出现Unexpected token 'export'错误

错误触发位置:

25 |   const store = setupStore();
  26 |
> 27 |   const { getByText } = render(
     |                               ^
  28 |     <Provider store={store}>
  29 |       <UserDisplay />
  30 |     </Provider>

该错误通常是Jest未转译ES模块语法的依赖包,或者配置存在冲突、重复项导致的。结合你给出的配置,以下是具体修复方案:


修复步骤

1. 修正Jest配置的冲突与遗漏

  • 移除重复的模块映射规则:moduleNameMapper里重复配置了.svg匹配,保留一个即可:
    moduleNameMapper: {
      '\\.(jpg|jpeg|png|gif|webp|svg)$': '<rootDir>/__mocks__/fileMock.js',
    },
    
  • 补充需要转译的测试库:在transformIgnorePatterns中加入@testing-library/react-native,确保该库的ES模块语法被转译:
    transformIgnorePatterns: [
      'node_modules/(?!(react-native|@react-native|@react-navigation|react-redux|@testing-library/react-native)/)',
    ],
    
  • 改用CommonJS格式导出配置:React Native的Jest预设更兼容CommonJS,调整配置文件格式:
    const { Config } = require('@jest/types');
    const config = {
      preset: 'react-native',
      transform: {
        '^.+\\.[tj]sx?$': 'babel-jest',
      },
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
      transformIgnorePatterns: [
        'node_modules/(?!(react-native|@react-native|@react-navigation|react-redux|@testing-library/react-native)/)',
      ],
      moduleNameMapper: {
        '\\.(jpg|jpeg|png|gif|webp|svg)$': '<rootDir>/__mocks__/fileMock.js',
      },
    };
    module.exports = config;
    

2. 简化Babel配置避免冲突

module:@react-native/babel-preset已经包含了@babel/preset-react和@babel/preset-env的核心配置,重复添加会导致冲突,简化后:

module.exports = {
  presets: [
    'module:@react-native/babel-preset',
    '@babel/preset-typescript',
  ],
  plugins: [
    ['@babel/plugin-transform-class-properties', { loose: true }],
    ['@babel/plugin-transform-private-methods', { loose: true }],
    ['@babel/plugin-transform-private-property-in-object', { loose: true }],
  ],
};

3. 调整TSConfig适配React Native

修改target和jsx配置,让TypeScript生成更兼容RN的代码:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "jsx": "react-native",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src", "__tests__"]
}

4. 检查版本兼容性

确保react-native、@testing-library/react-native、jest、babel-jest版本匹配:

  • React Native 0.70+建议搭配@testing-library/react-native 12.x及以上版本
  • 运行npm ls react-native @testing-library/react-native jest babel-jest查看版本,对照官方文档调整

5. 清除缓存

最后执行缓存清理,避免旧配置残留影响:

npx jest --clearCache

内容的提问来源于stack exchange,提问作者Prajwal VK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:52:24