I'm setting a pin
variable, updating it in cy.get()
and then trying to use it after the cy.get()
- it doesn't allow me to do this.
I've also read here that this is not possible: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-Values.
I really need to use this variable in order to be able to login: it's a generated PIN and I need to use it when logging in.
var pin = ""
cy.get('.pin-field').invoke('text').then((text1) => {
pin = text1; //assign text1 value to global pin variable, does not work
cy.log(text1) // this works and logs the value of text1
})
cy.log(pin) //this just logs an empty
The problem is in synchronization: The function invoke
returns a Promise, which is executed in async manner. The code cy.log(pin)
is executed just right after the invoke
is called and before the promise is resolved.
Try this:
cy.get('.pin-field').invoke('text').then(pin => {
cy.log(pin);
})
Or you can simulate synchronous behavior with async/await
:
async function login(cy) {
const pin = await cy.get('.pin-field').invoke('text'); // call it synchron
cy.log(pin); // this code executes when 'invoke` returned
}
Don't forget, the code with await
must be closed in an async
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With