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

运行JEST测试使用require引入node-fetch报错无法执行问题求助

问题根因
  • 你安装的node-fetch@3.x版本是纯ESM模块,仅支持import语法导入,不支持CommonJS的require()语法
  • Jest 27默认使用CommonJS模式运行,默认不会转换node_modules下的ESM模块代码,所以识别不了node-fetch里的import语句

方案1:降级node-fetch到v2版本(推荐新手使用)

node-fetch的v2版本同时支持CommonJS和ESM导入,不需要修改其他配置,直接执行命令卸载重装即可:

npm uninstall node-fetch
npm install node-fetch@2.x

装完之后重新运行npm test就能正常运行,不需要修改测试文件里的require('node-fetch')代码。


方案2:保留node-fetch v3,配置Jest支持ESM

如果你必须使用v3版本的node-fetch,可以按下面步骤修改配置:

  1. 首先修改测试文件script2.test.js的导入语法,替换为ESM的import写法:
import fetch from 'node-fetch';

it('test function', () => {
  expect(4).toEqual(4);
});
  1. 修改package.json里的test脚本,添加ESM支持的运行参数:
"scripts": {
  "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watchAll"
}
  1. 在package.json的jest配置块中添加transformIgnorePatterns配置,告诉Jest需要转换node-fetch的代码:
"jest": {
  "transform": {
    "^.+\\.(js|jsx)$": "babel-jest"
  },
  "transformIgnorePatterns": [
    "node_modules/(?!node-fetch)/"
  ],
  "extensionsToTreatAsEsm": [".js"]
}

修改完成后重新运行npm test即可正常执行测试。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:39:06