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

Jest报错ReferenceError: Response未定义问题求助

解决Jest中ReferenceError: Response is not defined及相关TypeScript类型问题

问题根源

你碰到的两个核心问题:

  • Response is not defined报错:Jest默认运行在Node.js环境里,而Response是浏览器专属的Web API对象,Node.js全局环境并没有内置它,直接调用new Response()自然会找不到这个对象。
  • TypeScript类型不匹配:你的HttpRequest函数声明返回Promise<Response>,但catch块里返回了null,这和声明的返回类型不一致,触发了TS类型检查错误。

分步解决方案

1. 让Jest环境支持Response对象

有两种实用方式可以解决这个问题:

方式一:借助node-fetch提供Response

node-fetch实现了浏览器的Fetch API,自带Response构造函数,适合不需要完整浏览器环境的场景:

  • 先安装依赖:
    npm install node-fetch --save-dev
    
  • 在测试文件中导入Response:
    import { Response } from 'node-fetch';
    
方式二:用JSDOM模拟完整浏览器环境

如果你的测试需要更多浏览器API支持,可以配置JSDOM:

  • 安装依赖:
    npm install jsdom --save-dev
    
  • 在测试文件顶部添加初始化代码:
    import { JSDOM } from 'jsdom';
    
    const dom = new JSDOM('', { url: 'http://localhost/' });
    global.Response = dom.window.Response;
    

2. 修正TypeScript类型错误

你的HttpRequest函数在出错时返回null,所以需要把返回类型调整为Promise<Response | null>,否则TS会报错:

const HttpRequest = async function (
  url: string,
  options: RequestInit,
): Promise<Response | null> { // 这里修改返回类型
  try {
    return await fetch(url, options);
  } catch (error) {
    return null;
  }
};
export default HttpRequest;

修正后的完整测试代码

这里以使用node-fetch的方案为例:

import { Response } from 'node-fetch';
import HttpRequest from './your-file-path'; // 替换为你的实际文件路径

describe('HttpService', () => {
  it('fetchWithFeedback', async () => {
    // 构造模拟的Response实例
    const mockRes = new Response(JSON.stringify({ data: 'test' }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
    
    // 模拟fetch函数的返回值
    global.fetch = jest.fn().mockResolvedValue(mockRes);

    const data = await HttpRequest('/api', { method: 'GET' });
    expect(data).toEqual(mockRes);
    expect(fetch).toHaveBeenCalledWith('/api', { method: 'GET' });
  });
});

额外小提示

如果你不想在每个测试文件都手动导入或初始化Response,可以在Jest的全局配置文件(比如jest.setup.ts)中统一配置JSDOM或导入node-fetch的Response,这样所有测试文件都能直接使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:57:32