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

如何模拟可解析为Response对象的Promise

解决Angular测试中Response.json()返回undefined的问题

我来帮你搞定这个测试难题——你遇到的info一直是undefined的问题,核心原因是测试时没有正确模拟item.promise,让它返回一个能正常调用.json()方法的Response对象。下面是具体的解决步骤:

核心思路

你需要让item.promise返回一个已决议的Promise,其值是一个合法的Response实例。这个Response要包含可被解析的JSON数据,这样调用.json()时才能得到预期的对象,而不是undefined。

具体实现方式

1. 手动构造模拟的BoxItems数组

在测试用例中,直接创建包含正确promise属性的mock数据:

// 模拟带有有效Response的boxItems
const mockBoxItems: BoxItems[] = [
  {
    promise: Promise.resolve(new Response(JSON.stringify({ id: 'test-id-1' })))
  },
  {
    promise: Promise.resolve(new Response(JSON.stringify({ id: 'test-id-2' })))
  }
];

这样当你的hasID方法执行await item.promise时,会得到一个真实的Response对象,调用.json()就能解析出里面的{ id: 'test-id-1' }这类数据,info就不会是undefined了。

2. 使用测试框架(Jasmine/Jest)模拟依赖

如果你的items是通过某个服务获取的,你可以用测试框架的spy功能来模拟服务的返回值:

用Jasmine的例子:

// 假设你有一个提供boxItems的服务
spyOn(yourBoxService, 'getItems').and.returnValue(
  of([
    {
      boxItems: [
        { promise: Promise.resolve(new Response(JSON.stringify({ id: 'spy-id' }))) }
      ]
    }
  ])
);

用Jest的例子:

jest.spyOn(yourBoxService, 'getItems').mockReturnValue(
  Promise.resolve([
    {
      boxItems: [
        { promise: Promise.resolve(new Response(JSON.stringify({ id: 'jest-id' }))) }
      ]
    }
  ])
);

3. 模拟无ID的场景(可选)

如果你需要测试hasID返回false的情况,只需要让Response中的JSON不包含id字段即可:

const mockBoxItemWithoutId = {
  promise: Promise.resolve(new Response(JSON.stringify({ name: 'no-id-item' })))
};

关键注意点

  • 确保item.promise的类型是Promise<Response>,而不是Promise<object>或者其他类型——普通对象没有.json()方法,这也是导致info为undefined的常见原因。
  • 用JSON.stringify()包装你的测试数据,因为Response构造函数接收的是字符串形式的内容,这样.json()才能正确解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:36:38