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

使用Jest编写JS集成测试时出现fetch未定义错误的解决求助

解决Jest测试中fetch未定义的问题

我使用Jest为JavaScript代码编写集成测试,尽管已安装node-fetch依赖,但运行测试时仍提示ReferenceError: fetch is not defined错误。请问该如何解决此问题?

我的配置与代码

package.json

{
  "name": "some-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest --testRegex='script/integration-tests/.*(int-test))\\.js?$'"
  },
  "devDependencies": {
    "jest": "^28.1.3",
    "node-fetch": "^2.6.7",
    "uglify-js": "3.16.2"
  }
}

/scripts/validator.js

function validate(){
    
    fetch(SOME_UENDPOINT_URL, {
        method: 'GET',
        mode: 'cors',
        credentials: 'include',
        headers:{
            'content-type': 'application/json',
        }
    }).then(response => {
        return response;
    }).then(data => {
        
    });     
}

Jest集成测试脚本

const{validate} = require('../scripts/validator');

describe('User validation', () => {

     test('Should authenticate user', ()=>{
         validate();
         //some basic assertion follows
      });   
});

解决方案

方案1:在业务代码中显式导入node-fetch

Node.js环境本身不内置fetch API,node-fetch作为第三方包,需要手动导入后才能使用。修改validator.js:

const fetch = require('node-fetch');

function validate(){
    fetch(SOME_UENDPOINT_URL, {
        // 原请求配置
    })
    // 原后续逻辑
}

如果项目使用ES模块语法,可改为import fetch from 'node-fetch';。

方案2:全局注入fetch到Jest环境

如果不想在每个使用fetch的文件中重复导入,可以配置Jest让fetch全局可用:

  1. 在项目根目录创建jest.setup.js文件,内容如下:
global.fetch = require('node-fetch');
  1. 修改package.json,添加Jest配置:
{
  // 原有配置...
  "jest": {
    "setupFiles": ["./jest.setup.js"]
  }
}

方案3:用Jest模拟fetch(适合控制测试依赖)

如果不需要发起真实网络请求,或者需要自定义返回结果,可以在测试文件中模拟fetch:

const { validate } = require('../scripts/validator');

// 全局模拟fetch
global.fetch = jest.fn(() => 
  Promise.resolve({
    // 模拟响应的方法,比如json()
    json: () => Promise.resolve({ status: 'success' })
  })
);

describe('User validation', () => {
  afterEach(() => {
    jest.clearAllMocks(); // 每次测试后清除模拟调用记录
  });

  test('Should authenticate user', ()=>{
      validate();
      expect(fetch).toHaveBeenCalledTimes(1); // 断言fetch被调用
      // 其他业务断言
  });   
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:12:27