如何等待Cypress的then()命令执行完成后再返回值?
问题原因
这是Cypress异步执行机制导致的问题:Cypress所有cy.开头的命令都会被加入异步执行队列,不会立刻运行,主线程会先执行完所有同步代码,所以你写在最后的return myNumber会在cy.get(...).then()的回调执行前就运行,此时变量还没被赋值,自然返回undefined。
修复方案
你不需要自己声明外部变量存储值,直接返回整个Cypress命令链即可,Cypress的命令链本身封装了类Promise逻辑,调用方可以通过.then()拿到返回值:
// 注意返回值类型改为Cypress.Chainable<string> public getValueFromElement(): Cypress.Chainable<string> { cy.log("Obtaining the Value"); // 直接返回cy.get的链式调用 return cy.get(this.labelWithText).then(($element) => { const originalLabelText: string = $element.text(); const splittedText: string[] = originalLabelText.split(": "); const myNumber = splittedText[1]; cy.log("Inside the THEN" + myNumber); // 在then回调末尾返回要对外传递的值 return myNumber; }); }
调用方式
调用该方法时不能直接用同步赋值的方式取值,需要用.then()接收异步返回的结果:
// 调用示例 this.getValueFromElement().then((myNumber) => { // 所有需要用到myNumber的逻辑都要写在这个then回调内 cy.log("拿到的数值为:" + myNumber); // 也可以直接接断言 // expect(myNumber).to.equal('你预期的值') })
内容的提问来源于stack exchange,提问作者Jorge
相关产品推荐
相关产品推荐

