【问题标题】:Cannot set a variable's value inside cypress command cy.get() to use outside the command无法在 cypress 命令 cy.get() 内设置变量值以在命令外使用
【发布时间】:2019-03-08 12:11:22
【问题描述】:

我正在设置一个pin 变量,在cy.get() 中更新它,然后在cy.get() 之后尝试使用它——它不允许我这样做。

我在这里也读到这是不可能的:https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-Values

我确实需要使用这个变量才能登录:它是一个生成的 PIN,我需要在登录时使用它。

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

【问题讨论】:

    标签: javascript cypress


    【解决方案1】:

    问题在于同步:函数invoke返回一个Promise,它以异步方式执行。代码cy.log(pin)invoke 被调用之后和promise 被解析之前执行。

    试试这个:

    cy.get('.pin-field').invoke('text').then(pin => {
        cy.log(pin);  
    })
    

    或者你可以用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
    }
    

    别忘了,await 的代码必须在 async 函数中关闭。

    【讨论】:

      【解决方案2】:

      您似乎正在为范围而苦苦挣扎。对我有用的是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-11
        • 2012-07-22
        • 1970-01-01
        • 2020-09-27
        • 2015-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多