如何在数组中查找没有名称的对象中的特定属性

问题描述 投票:0回答:1

我有一个 API,其响应如下所示(请注意,它是数组中没有名称的对象):

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

如何检查该API响应中是否存在属性分数?我尝试使用

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

还有许多其他想法,但没有任何效果。它总是会抛出错误

expected false to be true

cypress chai
1个回答
0
投票

您的断言实际上正在通过(根据您发布的代码),所以它看起来像

response
is提供数组

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

// original assertion passes
expect(response.offers.some(offer => {
  return offer.score !== undefined && typeof offer.score === "string"}
), 'original assertion passes').to.be.true

Cypress lodash 对于解析对象列表非常有用,这里有几个例子:

const score67 = Cypress._.find(response.offers, {score: "67"})
expect(score67).not.to.be.undefined

const score68 = Cypress._.find(response.offers, {score: "68"})
expect(score68).to.be.undefined

const firstWithScore = Cypress._.find(response.offers, 'score')
expect(firstWithScore.score).to.be.a('string')

const scores = Cypress._.flatMap(response.offers, (offer) => offer.score).filter(Boolean)
expect(scores).to.deep.equal(['67', '70'])
expect(scores.every(s => typeof s === 'string')).to.eq(true)

© www.soinside.com 2019 - 2024. All rights reserved.