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

Jest测试报错ReferenceError: Request未定义,求解决方案

解决Jest测试中ReferenceError: Request is not defined的问题

刚接触Jest遇到这种问题太正常啦!我来帮你理清原因和解决办法:

问题根源

Jest是运行在Node.js环境中的测试框架,而Request是浏览器端Fetch API的原生构造函数——Node.js默认并不提供这个API,所以当你的sendToServer函数里用到Request时,测试环境就会找不到它,抛出ReferenceError。

具体解决方案

根据你的代码场景,有几种不同的处理方式:

1. 为Node环境添加Fetch API的Polyfill

如果你的sendToServer确实依赖浏览器的Fetch API(包括Request),可以通过polyfill让Node环境支持它:

  • 首先安装依赖:
    npm install --save-dev whatwg-fetch
    
  • 然后在Jest配置文件(jest.config.js)中添加启动时自动加载的文件:
    module.exports = {
      setupFiles: ['whatwg-fetch']
    };
    
    或者直接在你的测试文件顶部导入polyfill:
    import 'whatwg-fetch';
    

2. 手动Mock Request构造函数

如果你不想引入polyfill,或者只是想测试sendToServer的逻辑而不是真实的Request行为,可以在测试文件中手动给全局对象添加Request的模拟实现:

// 在测试前定义模拟的Request类
global.Request = class Request {
  constructor(url, options) {
    // 这里可以根据你的需求模拟属性或方法
    this.url = url;
    this.method = options?.method || 'POST';
    this.body = options?.body;
  }
};

describe("Testing the API call", () => {
  test("Testing the API call", () => {
    sendToServer("Hey there!");
    // 后续还可以添加断言,比如检查Request是否被正确实例化
  })
})

3. Mock整个Fetch调用(更推荐的测试方式)

如果sendToServer最终是通过fetch发送请求,其实更推荐直接Mockfetch函数,这样既不需要依赖polyfill,也能更精准地测试逻辑:

// 模拟全局的fetch函数
global.fetch = jest.fn(() => 
  Promise.resolve({
    ok: true,
    json: () => Promise.resolve({ status: 'success' })
  })
);

describe("Testing the API call", () => {
  test("Testing the API call", async () => {
    // 注意如果sendToServer是异步函数,要加await
    await sendToServer("Hey there!");
    
    // 断言fetch被调用过
    expect(fetch).toHaveBeenCalled();
    // 还可以断言fetch的调用参数是否符合预期
    expect(fetch).toHaveBeenCalledWith(expect.any(Request));
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:58:46