最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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: .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

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
Share Improve this question edited Mar 8, 2019 at 12:36 ttulka 10.9k7 gold badges44 silver badges56 bronze badges asked Mar 8, 2019 at 12:11 reachfreedomreachfreedom 811 silver badge6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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.

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)
发布评论

评论列表(0)

  1. 暂无评论