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

使用Jest+React Testing Library时遇import语法错误求助

解决React Testing Library + Jest中「SyntaxError: Cannot use import statement outside a module」错误

问题背景

我刚开始使用React Testing Library结合Jest开发一个模拟服务器交互的示例应用,Node版本为v16.13.0。运行测试时出现「SyntaxError: Cannot use import statement outside a module」错误,即使修改axios导入路径为import axios from './lib/axios'也无法解决。

错误详情

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:

D:\test-projects\icecream\node_modules\axios\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

> 1 | import axios from "axios";
    | ^
  2 | import { useEffect, useState } from "react";
  3 | import { Row } from "react-bootstrap";
  4 | import ScoopOption from "./ScoopOptions";

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (src/pages/entry/Options.jsx:1:1)

相关代码

测试代码

import Options from "../Options";
import { render, screen } from "@testing-library/jest-dom";
test("displays image for each scoop option from the server", async () => {
  render(<Options optionType="scoop" />);
  const scoopImages = await screen.findAllByRole("img", { name: /scoop$/i });
  expect(scoopImages).toHaveLength(2);
});

Options.jsx核心代码

import axios from "axios";
const [items, setItems] = useState([]);
useEffect(() => {
  axios
    .get(`http://localhost:3030/${optionType}`)
    .then((response) => setItems(response.data))
    .catch((err) => {});
}, [optionType]);

package.json配置

{
  "name": "icecream",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "@babel/plugin-transform-modules-commonjs": "^7.20.11",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "axios": "^1.2.1",
    "bootstrap": "^5.2.3",
    "eslint-plugin-jest-dom": "^4.0.3",
    "eslint-plugin-testing-library": "^5.9.1",
    "msw": "^0.49.2",
    "react": "^18.2.0",
    "react-bootstrap": "^2.7.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/preset-env": "^7.20.2",
    "@testing-library/user-event": "^14.4.3",
    "babel-jest": "^29.3.1"
  }
}

解决方案

1. 修正测试代码的导入错误

render和screen应该从@testing-library/react导入,@testing-library/jest-dom仅用于扩展断言方法,修正后的测试代码:

import Options from "../Options";
import { render, screen } from "@testing-library/react";
import '@testing-library/jest-dom'; // 用于扩展expect的断言方法

test("displays image for each scoop option from the server", async () => {
  render(<Options optionType="scoop" />);
  const scoopImages = await screen.findAllByRole("img", { name: /scoop$/i });
  expect(scoopImages).toHaveLength(2);
});

2. 配置Jest转换axios模块

由于axios v1.x默认使用ESM格式,而Jest默认忽略node_modules目录的代码转换,需要修改Jest配置,让它转换axios模块。在package.json中添加jest配置:

{
  // ... 原有配置
  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!axios)/"
    ]
  }
}

这个配置表示:除了axios之外,忽略node_modules中其他模块的转换。

3. 完善Babel配置

在项目根目录创建babel.config.json文件,确保Babel能将ESM转换为Jest支持的CommonJS:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-transform-modules-commonjs"
  ]
}

4. 适配ESM环境(可选)

如果上述配置仍不生效,因为你的package.json中设置了"type": "module",可以创建jest.config.mjs文件(注意是.mjs后缀):

export default {
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest',
  },
  transformIgnorePatterns: [
    'node_modules/(?!axios)/',
  ],
};

完成以上配置后,重新运行测试即可解决该错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:50:36