-1

Here is my code snippet:

verifyBookingSuccess(){

 cy.findByTitle(/created/i).parent().parent().then(async($ele)=>{
      bookingId= ($ele.attr("href").split("/"))[2]
      cy.log("Booking ID:"+bookingId)
    })
return bookingId;
}

I can able to read the bookingId value inside the then() method. But Outside am unable to access it. Is there any way to access that bookingId value?

imBollaveni
  • 99
  • 1
  • 13
  • See https://docs.cypress.io/guides/core-concepts/variables-and-aliases – jonrsharpe Nov 02 '21 at 07:44
  • @jonrsharpe - Already checked that page. still no use. – imBollaveni Nov 02 '21 at 08:09
  • No, there is no way to access that value (other than those listed on the page above). Cypress has its own model for handling the asynchronous nature of driving the browser. And even if it didn't, you'd be falling into the standard problem described by https://stackoverflow.com/q/14220321/3001761. – jonrsharpe Nov 02 '21 at 11:24

2 Answers2

0

You have to use aliases as pointed out by @jonrsharpe You can do something like this:

it('Some Test', () => {
  //Some Other code
  cy.findByTitle(/created/i)
    .parent()
    .parent()
    .invoke('attr', 'href')
    .then((text) => {
      cy.wrap((text.split('/'))[2]).as('hrefValue')
    })
  //Some Other code
  cy.get('@hrefValue').then((hrefValue) => {
    cy.log(hrefValue) //prints the href value
  })
})

Note: This will only work if the alias value is used in the same test as it was stored in.

Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • I want assign that href value to a variable or return as value of any javascript method,. not like again use in some other then() method . – imBollaveni Nov 02 '21 at 08:14
  • `.as('hrefValue')` is how you assign value to a variable in cypress. Now to access the value stored in `hrefValue` variable, you have to use a `then()`. – Alapan Das Nov 02 '21 at 08:16
  • If I use `then()` method then `return` wont work. modified code in my question. check it once. – imBollaveni Nov 02 '21 at 10:23
0

I'm able to retrieve the value outside of then() method using Cypress.env

verifyBookingSuccess(){

 cy.findByTitle(/created/i).parent().parent().then(async($ele)=>{
      var bookingId= ($ele.attr("href").split("/"))[2]
      cy.log("Booking ID:"+bookingId)
      Cypress.env("bookingId", bookingId);

    })
return Cypress.env("bookingId");
}

find more info at: https://docs.cypress.io/api/cypress-api/env#Name-and-Value

imBollaveni
  • 99
  • 1
  • 13