React项目安装Jest后运行测试出现Import语句错误
React项目Jest测试报错:Cannot use import statement outside a module
在React项目中安装Jest后运行测试,出现如下错误:
● 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: • 如果你在使用ECMAScript Modules,需要配置Jest以支持它。 • 如果你在使用TypeScript,需确保Jest已配置支持TypeScript。 • 若需要转译部分"node_modules"文件,可在配置中指定自定义的"transformIgnorePatterns"。 • 若需要自定义转译规则,可在配置中添加"transform"选项。 • 若只是想mock非JS模块(比如二进制资源),可使用"moduleNameMapper"配置选项来替换它们。 你可以在Jest配置文档中找到这些选项的更多细节和示例,自定义转译的相关信息也可在对应文档中查看。 Details: C:\Users\Pos\Desktop\live-projects\git-lab\new-clone\chan\restaurant-pos-v1-react\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 | // import varaiable 4 | import { at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14) at Object.<anonymous> (src/api/index.js:1:1) at Object.<anonymous> (src/actions/credit-sale/creditSale_CustomAction.js:1:1) at Object.<anonymous> (src/components/creditSale/creditSaleSearchBar.jsx:4:1) at Object.<anonymous> (src/pages/creditSale/creditSale.jsx:5:1) at Object.<anonymous> (src/__test__/pages/creditSale/creditSale.test.js:2:1) at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13) at runJest (node_modules/@jest/core/build/runJest.js:404:19)
测试套件结果:1个失败,共1个;测试用例:0个;快照:0个;耗时:4.375秒;已运行所有与修改文件相关的测试套件。
错误原因
axios当前采用ES模块语法(import/export),但Jest默认会跳过node_modules目录下文件的转译,导致无法识别import语句,从而抛出语法错误。
解决方案
方案1:配置Jest转译axios
在项目的Jest配置文件(jest.config.js或package.json中的jest字段)中,修改transformIgnorePatterns,将axios排除在忽略转译的列表之外:
- 若使用
jest.config.js:
module.exports = { // 保留原有其他配置 transformIgnorePatterns: [ 'node_modules/(?!(axios)/)', ], };
- 若在
package.json中配置:
{ "jest": { "transformIgnorePatterns": ["node_modules/(?!(axios)/)"] } }
该配置表示Jest会对node_modules下的axios目录进行转译,而非跳过。
方案2:适配ES模块项目(package.json含"type": "module")
如果你的项目已配置为ES模块(package.json中有"type": "module"),需额外做以下配置:
- 在
jest.config.js中添加:
module.exports = { // 保留原有其他配置 transform: {}, extensionsToTreatAsEsm: ['.js', '.jsx'], };
- 修改
package.json中的测试命令,添加Node.js实验性模块参数:
{ "scripts": { "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" } }
方案3:手动Mock axios(临时快速解决)
若只是想让测试快速运行,可手动Mock axios模块,避免加载真实的axios文件:
在测试文件顶部添加:
jest.mock('axios', () => ({ default: jest.fn(() => Promise.resolve({ data: {} })), }));
测试会使用Mock的axios,不会触发真实模块的语法错误。
内容的提问来源于stack exchange,提问作者Chandru Logan
相关产品推荐
相关产品推荐

