-1
describe('test', function() {

    
it('array check', function() {

    let variable = 'Variable1'

    
    cy.visit('https://www.google.com')
    .then(function() {
        this.variable = 'Variable2'
    })
    cy.log(variable)  // Why it's still Variable1?
})

})

I want to change variable in .then block and after that re-use it outside of .then block. But I can't.

Edward K
  • 25
  • 2
  • Of course you can't; it's asynchronous, that's _why_ there's a callback. See https://stackoverflow.com/q/14220321/3001761 generally and https://docs.cypress.io/guides/core-concepts/variables-and-aliases specifically. – jonrsharpe Oct 26 '22 at 14:14
  • I'd suggest reading some documentation on Promises and asynchronous code. Your `.then` hasn't happened yet when the value is logged. – DBS Oct 26 '22 at 14:14
  • 1
    Does this answer your question? [How to access cypress.env file from another test file](https://stackoverflow.com/questions/76037549/how-to-access-cypress-env-file-from-another-test-file) – user16695029 Apr 25 '23 at 00:35

1 Answers1

0

Gleb explains this issue here:

Cypress commands are asynchronous, but they are also chained first. When Cypress runs through the test the first time, it only internally queues the commands for execution. Every command is stored as an object in Cypress memory together with its arguments. In JavaScript, when you call a function, the primitive arguments are passed by value. Each argument's value at the moment of the call is copied and passed into the function.

So, essentially the cy.log() is queued with the value of variable when it is chained, and not the value of variable when cy.log() is called.

In order to solve this, you'll need to add some additional chaining:

    let variable = 'Variable1'

    cy.visit('https://www.google.com')
    .then(function() {
        this.variable = 'Variable2'
    })
    .then(function() {
        cy.log(variable)
    })
agoff
  • 5,818
  • 1
  • 7
  • 20