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

如何检测API响应数组中无名对象的score属性是否存在?

问题:API响应中检查score属性存在性的测试失败

我有一个API,其响应格式如下(数组内是无命名对象):

{
 offers: [
  {
   sticker: null,
  },
  {
   sticker: null,
   score: "67",
  },
  {
   sticker: null,
  },
  {
   sticker: null,
  },
  {
   sticker: null,
   score: "70",
  }
 ]
}

我需要检查该API响应中是否存在score属性,尝试使用以下代码:

expect(resp.body.offers.some((offer: any) => offer.score !== undefined && typeof offer.score === "string")).to.be.true;

但多次尝试均无效,始终抛出错误expected false to be true,请问该如何解决?


解决方案及分析

先排查核心问题点

  • 确认响应结构是否匹配预期:在测试代码里先打印resp.body.offers,排查是否存在字段名写错(比如大小写错误Offers)、数组为空,或者响应未被正确解析成JSON的情况。
  • 检查score的实际类型:如果API返回的score是数字(比如67而非"67"),那typeof offer.score === "string"判断会不成立,直接导致整个断言返回false。

修正后的测试代码

方案1:兼容字符串/数字类型的score

如果业务允许score是字符串或数字,调整判断逻辑:

expect(resp.body.offers.some((offer: any) => {
  return 'score' in offer && (typeof offer.score === "string" || typeof offer.score === "number");
})).to.be.true;

方案2:仅检查score属性是否存在

如果不需要严格验证类型,只确认属性存在:

expect(resp.body.offers.some((offer: any) => Object.prototype.hasOwnProperty.call(offer, 'score'))).to.be.true;

方案3:先验证数组有效性

避免因为数组不存在或为空导致的错误:

// 先确保offers是有效数组
expect(Array.isArray(resp.body.offers)).to.be.true;
// 再检查存在score属性的项
expect(resp.body.offers.some((offer: any) => 'score' in offer)).to.be.true;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:00:13