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

React Native TypeScript项目Jest测试报错:Cannot use import statement outside a module

解决Expo + TypeScript项目中Jest的「SyntaxError: Cannot use import statement outside a module」错误

这个错误的核心是Jest未正确解析TypeScript/ES模块语法,以下是针对性的配置调整方案:

1. 修正Babel配置(babel.config.js)

确保Babel在测试环境下将ES模块转换为CommonJS,同时兼容Expo和TypeScript:

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo', ['@babel/preset-typescript', { allowNamespaces: true }]],
    env: {
      test: {
        presets: [
          ['@babel/preset-env', { targets: { node: 'current' } }],
          '@babel/preset-typescript'
        ],
        plugins: ['@babel/plugin-transform-modules-commonjs']
      }
    }
  };
};

2. 调整Jest配置(jest.config.js)

使用Expo官方的Jest预设,避免与ts-jest冲突,同时明确TypeScript文件的转换规则:

module.exports = {
  preset: 'jest-expo',
  transform: {
    '^.+\\.(ts|tsx)$': 'babel-jest'
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  testEnvironment: 'node',
  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)'
  ]
};

3. 校验依赖与package.json配置

  • 确保安装了必要依赖:
    npm install --save-dev @babel/preset-typescript babel-jest jest-expo
    
  • 移除package.json中可能存在的"type": "module"字段(该配置会让Node默认以ES模块解析,与Jest的CommonJS处理逻辑冲突)
  • 测试脚本保持为:
    "scripts": {
      "test": "jest"
    }
    

4. 检查测试文件规范

  • 测试文件命名需符合Jest识别规则,如Feed.test.tsx或Feed.spec.tsx
  • 确保测试文件中的import语法正确,示例:
    import React from 'react';
    import { render } from '@testing-library/react-native';
    import Feed from '../Feed';
    
    test('renders Feed component correctly', () => {
      const { getByTestId } = render(<Feed />);
      // 这里添加你的断言逻辑,比如:
      // expect(getByTestId('feed-container')).toBeTruthy();
    });
    

5. 清除缓存并重新测试

执行以下命令清除Jest缓存,避免旧配置残留:

npx jest --clearCache

之后再运行测试命令即可。

关键说明

不要同时使用ts-jest和jest-expo,Expo的Jest预设已经内置了TypeScript处理能力,单独引入ts-jest会导致模块解析逻辑冲突,这也是你之前尝试后问题未解决的核心原因。

内容的提问来源于stack exchange,提问作者Angel Rafael

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 14:16:30