Trying to stores the data in .as command but its returning Null when recalled using This.text

Viewed 23

I'm trying to store a variable using .as command which stores the data but its returning Null when recalled using This.text

it('store variable',function(){

cy.log('ASDF').as('print')
}

it('print',function(){
cy.log(This.print)
}
2 Answers

It's because cy.log() does not yield anything. Look at the docs, each command has a Yields section to let you know what gets passed to chained commands like .as().

You want to use cy.wrap() instead.

cy.wrap('ASDF').as('print')

Also don't use a capital T on this

cy.log(this.print)

Assuming that you want to use the value saved in one it block to another. Aliases (as) won't be the right choice because cypress clears aliases between it blocks.

What you can use is the cypress environment variables to save your text, then you can use that text anywhere throughout your cypress project.

it('store variable', function () {
  cy.get('selector')
    .invoke('text')
    .then((text) => {
      Cypress.env('envVarText', text) //Saves the value
    })
})

it('print', function () {
  cy.log(Cypress.env('envVarText')) //gets the value
})

In case if you want to wrap the text, you can do this:

it('store variable', function () {
  cy.wrap('ASDF').then((text) => {
    Cypress.env('envVarText', text) //Saves the value
  })
})

it('print', function () {
  cy.log(Cypress.env('envVarText')) //gets the value
})
Related