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

React Native中Jest运行test.tsx遇意外token错误求助

React Native Jest测试报错:Unexpected token '<'

问题详情

使用React Native 0.71.7版本,运行测试时触发Jest无法解析JSX语法的错误,尝试多种配置调整仍未解决,错误信息如下:

FAIL tests/App.test.tsx
● 测试套件运行失败

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/Users/mmt10901/Desktop/Code/B2B-Shopfront-Mobile/__tests__/App.test.tsx:37
    const component = renderer.create(<App_1.NavBody />);
                                      ^

SyntaxError: Unexpected token '<'

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1495:14)

当前相关配置

Jest配置(jest.config.js)

module.exports = {
    preset: "ts-jest",
    testEnvironment: "node",
    setupFiles: ['./node_modules/react-native-gesture-handler/jestSetup.js'],

    setupFilesAfterEnv: ["<rootDir>/setupTests.js"],
    transformIgnorePatterns: [
        "node_modules/(?!(react-native|@react-native|@babel|ts-js)/)",
    ],
    moduleNameMapper: {
        '\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
            '<rootDir>/assetsTransformer.js',
        '\.(css|less)$': '<rootDir>/assetsTransformer.js',
    },
    transform: {
        "\.tsx?$": "ts-jest",
        "\.jsx?$": "babel-jest",
    },
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
    extensionsToTreatAsEsm: ['.ts', '.tsx'],
};

Babel配置(babel.config.js)

module.exports = (api) => {
  api.cache(false);

  return {
    presets: [
      "module:metro-react-native-babel-preset",
      "@babel/preset-typescript",
    ],
    plugins: [
      [
        "module:react-native-dotenv",
        {
          envName: "APP_ENV",
          moduleName: "@env",
          path: ".env",
          safe: false,
          allowUndefined: true,
          verbose: false,
        },
      ],
    ],
  };
};

TypeScript配置(tsconfig.json)

{
  "extends": "@tsconfig/react-native/tsconfig.json",
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "checkJs": true,
    "noEmit": true,
    "strict": false,
    "sourceMap": true,
    "noImplicitAny": false,
    "baseUrl": "./",
    "types": ["jest", "node"],
    "typeRoots": ["./src/types"],
    "paths": {
      "@/*": ["./*"]
    },
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": [
    ".eslintrc.js",
    "*.ts",
    "*.tsx",
    "src/**/*.ts",
    "src/**/*.tsx",
    "*/*.d.tsx",
    "*/**.d.ts",
    "./tsconfig.json",
    "./babel.config.js",
    "./jest.config.js"
  ],
  "exclude": ["node_modules"],
  "esModuleInterop": true
}

解决方案

1. 替换Jest预设与测试环境

React Native项目不能用ts-jest作为预设,也不能使用node作为测试环境,替换为React Native专用预设:

// jest.config.js
module.exports = {
  preset: 'react-native', // 替换原有的ts-jest
  // 移除testEnvironment: "node",react-native预设会自动配置合适的环境
  // ...其他保留的配置项
};

react-native预设已内置对JSX、TypeScript和React Native代码的支持,无需单独配置ts-jest和babel-jest的转换规则。

2. 修正Transform规则

如果需要保留自定义转换,统一用babel-jest处理所有JS/TS文件,确保JSX被正确转换:

// jest.config.js
transform: {
  '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
},

3. 修复Transform Ignore Patterns

移除错误的ts-js项,确保所有React Native相关依赖都被转换:

transformIgnorePatterns: [
  'node_modules/(?!(react-native|@react-native|@react-native-community|@babel)/)',
],

4. 清理ESM冲突配置

若未明确使用ESM,移除extensionsToTreatAsEsm避免与CommonJS配置冲突:

// 从jest.config.js中删除此行
// extensionsToTreatAsEsm: ['.ts', '.tsx'],

5. 检查setupTests.js配置

确保测试前置文件包含必要的React Native测试扩展:

// setupTests.js
import '@testing-library/jest-native/extend-expect';
import 'react-native-gesture-handler/jestSetup';

内容的提问来源于stack exchange,提问作者Arpit Malik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:17:37