React项目使用axios遇Jest测试报错:Cannot use import statement outside a module
解决React+Jest测试中Axios的"Cannot use import statement outside a module"错误
问题背景
我在React项目中结合MUI开发样式,用Axios实现请求功能,开发阶段无任何报错。但使用React Testing Library和Jest编写组件测试时,出现Axios模块错误:Cannot use import statement outside a module。查阅资料后推测是Axios将模块类型从CommonJS改为ECMAScript导致,尝试过适用于Vue.js的解决方案但未成功。
报错信息
FAIL src/components/user/Contact.test.js ● Test suite failed to run 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:\Programs\VS Code\Web Development\lmsfrontend\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 | 3 | const API_URL = "https://librarymngsys.adaptable.app/api/user"; 4 | at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14) at Object.<anonymous> (src/features/user/userService.js:1:1) Test Suites: 1 failed, 1 total Tests: 0 total Snapshots: 0 total Time: 1.254 s Ran all test suites related to changed files.
测试代码
import { render, screen } from "@testing-library/react"; import Contact from "./Contact"; describe("Contact", () => { test("renders correctly", () => { render(<Contact />); const inputElem = screen.getByLabelText(/Name/) expect(inputElem).toBeInTheDocument(); }); });
组件相关代码
const Contact = () => { // 其他逻辑代码 return ( <Box> <Box><Typography variant="h2" sx={{ textAlign: 'center' }}>Contact Us</Typography></Box> <Card sx={{ minHeight: '77vh', boxShadow: '1px 2px #3f48f2' }}> <Box sx={{ m: 1 }}> <TextField required fullWidth id="contact-name" label="Name" name="name" value={values.name} onChange={handleChange} onBlur={handleBlur} helperText={errors.name && touched.name ? errors.name : null} error={errors.name && touched.name} /> </Box> <Box sx={{ m: 1 }}> <TextField required fullWidth id="contact-mail" label="E-Mail ID" name="mail" value={values.mail} onChange={handleChange} onBlur={handleBlur} helperText={errors.mail && touched.mail ? errors.mail : null} error={errors.mail && touched.mail} /> </Box> </Card> </Box> ) } export default Contact
解决方法
方法1:修改Jest配置,转译Axios
Jest默认不转译node_modules中的文件,而新版Axios是ES模块,需要配置让Babel转译它:
在jest.config.js(或package.json的jest字段)中添加:
module.exports = { // 保留原有其他配置 transformIgnorePatterns: [ 'node_modules/(?!axios/)' ] };
方法2:Mock Axios模块
测试组件时无需真实请求,直接Mock Axios可以绕过模块类型问题:
- 方式一:在测试文件顶部添加Mock
jest.mock('axios', () => ({ default: jest.fn(() => Promise.resolve({ data: {} })) }));
- 方式二:创建全局Mock
在项目根目录创建__mocks__/axios.js文件:
export default { get: jest.fn(() => Promise.resolve({ data: {} })), post: jest.fn(() => Promise.resolve({ data: {} })) // 根据需求添加其他Axios方法 };
Jest会自动识别并使用这个Mock。
方法3:降级Axios版本
如果不想修改配置,可以降级到仍使用CommonJS模块的Axios版本:
npm install axios@0.27.2 --save
内容的提问来源于stack exchange,提问作者Roshan Shetty
相关产品推荐
相关产品推荐

