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)
})