Home > Software engineering >  Cypress- cannot read properties of undefined
Cypress- cannot read properties of undefined

Time:07-13

I have such a problem that cypress cannot find the properties. In response I get array. I want to find record and get CustomMessage. :) Do you notice where I am making a mistake:/ ? console response

cypress error

Here is my code :)

cy.request({
    method: 'GET',
    url: 'url',
  })
    .then((resp) => resp.body)
    .then((data) =>
      data.find((element) => element['body']['Message']['Phone'] == phone)
    )
    .then((phone) => (otpCode = phone['body']['Message']['CustomMessage']))

Thanks for any help :)

CodePudding user response:

The problem is nothing in the array matches phone

Try adding a guard

cy.request(...)
  .then((resp) => resp.body)
  .then((data) => {
    const found = data.find((element) => element.body.Message.Phone === phone)
    if (!found) throw 'Error: phone not found'
    return found
  })
  .then((phone) => {
    otpCode = phone.body.Message.CustomMessage
  })

The way you have it originally, when data.find() fails the whole array is passed on to the otpCode extraction.

CodePudding user response:

You can get the customMessage like this:

cy.request({
  method: 'GET',
  url: 'url',
}).then((resp) => {
  const customMessage = resp.body[1].body.Message.customMessage
})

CodePudding user response:

Make it simple with cy-spok.

const 'spok' = require('cy-spok')


cy.request({
    method: 'GET',
    url: 'url',
  })
  // access properties with .its()
  .its('response.body')
  .its(1)
  .should(spok({
    Message: {
      Phone: spok.string // or us spok.test to check string length as well
    }
  // now we verified the response has Message.Phone let's extract it
  .its('Message.Phone')
  .as('otpCode')
  • Related