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

Node环境Jest配置node-fetch polyfill遇require/类构造函数错误排查

解决Jest Node环境中node-fetch Polyfill的配置问题

处理node-fetch v3的ERR_REQUIRE_ESM错误

node-fetch v3是纯ESM包,Node v16的CommonJS模块无法直接require,需调整Jest和Babel配置适配:

  • 修改jest.config.js,添加transformIgnorePatterns排除node-fetch,确保Babel能处理该包:
    module.exports = {
      transform: {
        '^.+\\.(js|jsx)$': 'babel-jest',
      },
      transformIgnorePatterns: [
        'node_modules/(?!node-fetch)'
      ],
      testEnvironment: 'node'
    };
    
  • 在Babel配置文件(.babelrc或babel.config.js)中启用对应Node版本的ESM支持:
    module.exports = {
      presets: [
        ['@babel/preset-env', { targets: { node: '16' } }]
      ]
    };
    
  • 在测试前置文件或单个测试文件中用动态import加载polyfill:
    async function polyfillFetch() {
      const { Headers, Request, Response } = await import('node-fetch');
      global.Headers = Headers;
      global.Request = Request;
      global.Response = Response;
    }
    
    beforeAll(async () => {
      await polyfillFetch();
    });
    

解决node-fetch v2的"Class constructor Request cannot be invoked without 'new'"错误

该错误是Babel转译时将ES6类转为ES5构造函数导致的,可通过以下方式修复:

  • 在Babel配置中排除node-fetch的转译:
    module.exports = {
      presets: [['@babel/preset-env', { targets: { node: '16' } }]],
      exclude: /node_modules\/node-fetch/
    };
    
  • 或者在Jest配置的transformIgnorePatterns中排除node-fetch:
    module.exports = {
      transformIgnorePatterns: ['node_modules/(?!node-fetch)'],
      // 其他配置项...
    };
    

修复IDE与命令行执行不一致问题

PHPStorm和命令行执行结果不同,通常是环境或配置缓存差异导致:

  • 确认命令行Node版本与IDE一致:执行node -v,对比IDE中配置的Node版本,确保都是v16.20.2。
  • 检查IDE是否自动加载了项目.env等配置文件,命令行执行前手动加载(如source .env)。
  • 清除Jest缓存:命令行执行jest --clearCache,避免缓存导致配置不生效。

替代方案:使用cross-fetch

若上述配置仍有问题,可切换到cross-fetch,它同时支持CommonJS和ESM,无需复杂配置:

  • 安装依赖:npm install cross-fetch --save-dev
  • 创建jest.polyfill.js文件写入polyfill代码:
    const { Headers, Request, Response } = require('cross-fetch');
    global.Headers = Headers;
    global.Request = Request;
    global.Response = Response;
    
  • 在Jest配置中指定该前置文件:
    module.exports = {
      setupFilesAfterEnv: ['./jest.polyfill.js'],
      // 其他配置项...
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:02:12