reachfreedom
reachfreedom

Reputation: 81

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

Upvotes: 7

Views: 7710

Answers (2)

ttulka
ttulka

Reputation: 10882

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.

Upvotes: 3

Mr. J.
Mr. J.

Reputation: 3731

Seems like you are struggling with the scope. What works for me is this:

    cy.get('.original_object')
      .then($value => {
        const retreivedValue = $value.text()
    cy.get('.test_object')
      .should('contain', retreivedValue)

Upvotes: 2

Related Questions