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

使用Jest测试React项目时遭遇import语法错误求助

Fixing the "Unexpected token import" Error in React Jest Tests

Hey there! That error you're hitting happens because Jest doesn't natively support ES6 import syntax out of the box—it's built to work with CommonJS require statements by default. Since your test file is using React with ES6 imports, we need to set up Babel to translate that syntax into something Jest can understand.

Let's walk through the solution step by step:

1. Install Required Babel Dependencies

First, install the necessary Babel packages to handle React and ES6 transpilation:

npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-jest

2. Create/Update Your Babel Configuration

Create a .babelrc file in your project root (or modify an existing one) with these presets:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

This tells Babel to transpile both modern JavaScript (via preset-env) and React JSX/ES6 imports (via preset-react).

3. Verify Jest Configuration (If Needed)

Most modern setups will auto-detect Babel, but if you have a custom Jest config (like in package.json or jest.config.js), make sure it uses babel-jest as the transformer:

// In package.json
{
  "jest": {
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest"
    }
  }
}

4. Run Your Test Again

After setting this up, run your test command (usually npm test or jest)—the import syntax should now be properly transpiled, and your test should run without the syntax error.

Let's recap your original code and error for context:

Your Test Code:

import React from 'react';
test('Should render Loading correctly', () => { });

The Error You Saw:

● Test suite failed to run
/home/tul1/Desktop/proyectos/inorbit/web/tests/components/Loading.test.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
^^^^^^
SyntaxError: Unexpected token import

If you still run into issues, double-check that all dependencies are installed correctly and your Babel config is in the project root where Jest can find it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:57:25