Cypress: Invoking text and assigning to a variable, but not able to use?

Viewed 63

This code is working fine.

var txt
        cy.visit('https://dev.wholesoftmarket.com/account/signup')
        cy.get('label[for="exampleInputEmail1"]').invoke('text').then((text)=>{
            txt = text
            cy.get('#exampleInputPassword1').type(txt)
        })

This is not working, though I am getting an error of "You passed in: undefined". I am not sure how this works!

var txt
        cy.visit('https://dev.wholesoftmarket.com/account/signup')
        cy.get('label[for="exampleInputEmail1"]').invoke('text').then((text)=>{
            txt = text
        })
        cy.get('#exampleInputPassword1').type(txt)

Can someone explain how this working?

2 Answers

Cypress preference is to use alias instead of variables. You can read more about it here Variables and aliases.

cy.visit('https://dev.wholesoftmarket.com/account/signup')
cy.get('label[for="exampleInputEmail1"]').invoke('text')
  .as('labelText')

// later in the test
cy.get('@labelText').then(txt => {
  cy.get('#exampleInputPassword1').type(txt)
})

You don't need the global variable text, you can do directly like this:

cy.visit('https://dev.wholesoftmarket.com/account/signup')
cy.get('label[for="exampleInputEmail1"]')
  .invoke('text')
  .then((text) => {
    cy.get('#exampleInputPassword1').type(text)
  })

Because of the asynchronous nature of javascript, the txt value is used before it is getting updated with the inner text value. To prevent that you have to use a then like this:

var txt
cy.visit('https://dev.wholesoftmarket.com/account/signup')
cy.get('label[for="exampleInputEmail1"]')
  .invoke('text')
  .then((text) => {
    txt = text
  })
  .then(() => {
    cy.get('#exampleInputPassword1').type(txt)
  })

Another way would be to use the Cypress.env() variable, if you want to use the text value anywhere within the project or test.

cy.visit('https://dev.wholesoftmarket.com/account/signup')
cy.get('label[for="exampleInputEmail1"]')
  .invoke('text')
  .then((text) => {
    Cypress.env('label', text) //Set the text
  })
cy.get('#exampleInputPassword1').type(Cypress.env('label')) //Get text and type
Related