Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set a variable's value inside cypress command cy.get() to use outside the command

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
like image 450
reachfreedom Avatar asked Mar 08 '19 12:03

reachfreedom


1 Answers

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.

like image 146
ttulka Avatar answered Sep 30 '22 05:09

ttulka