cypresschai

How to find specific property in objects without name in array


I have an API whose response looks like this (notice that it is objects without name in array):

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

How to check if the property score exists in this API response? I tried using

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

and many other ideas I had but nothing works. It will always throw error expected false to be true.


Solution

  • Your assertion is actually passing (according to the code you posted), so it looks like the response is the offers array

    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 is really useful for parsing object lists, here's a few examples:

    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)
    

    enter image description here