【问题标题】:Cypress.io: Waiting for results of exec commandCypress.io:等待 exec 命令的结果
【发布时间】:2019-05-28 21:38:09
【问题描述】:

我正在尝试根据cy.exec() 命令的结果设置一些变量,以便稍后在脚本中使用。例如:

cy.exec('some command').then((result) => {
  let json = JSON.parse(result.stdout)
  this.foo = json.foo
})

如何等待this.foo 被定义,然后再继续执行脚本的其余部分?我试过了:

cy.exec('some command').as('results')
cy.wait('@results')

但是,this.resultscy.wait() 命令之后未定义。

【问题讨论】:

    标签: cypress


    【解决方案1】:

    您不需要别名。你的代码是正确的,但是you can't use this inside of a () => {}。您应该使用function 声明来使用this

    试试这个:

    cy.exec('some command').then(function(result) {
      let json = JSON.parse(result.stdout)
      this.foo = json.foo
    })
    

    请注意,赛普拉斯是异步的。这意味着如果你这样做:

    cy.exec('some command').then(function(result) {
      let json = JSON.parse(result.stdout)
      this.foo = json.foo
    })
    
    expect(this.foo).to.eq(expectedStdout)
    

    ...你的测试总是会失败。 this.foo = json.foo 将在评估expect(this.foo)... 之后执行

    如果你想以这种方式使用this.foo,只需使用cy.exec()返回的Promise即可:

    cy.exec('some command').then(result => {
      return JSON.parse(result.stdout)
    })
    .then(json => {
      // write the rest of your test here
      cy.get('blah').contains(json.something)
    })
    

    【讨论】:

    • 如何在“then”块之外的其他测试中引用 json.something 的值?
    • 你不能,它是异步的
    • 你可以从 beforeEach 中返回 Promise,然后它会在你的测试之前运行
    • 啊,使用钩子是我缺少的部分。将我的设置代码放在 before() 中而不尝试在箭头函数中使用 this 的组合是我的解决方案。
    猜你喜欢
    • 2011-04-18
    • 2016-03-30
    • 2019-01-27
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多