Return 来自赛普拉斯异步块的值?

Return a value from an async block in Cypress?

我正在尝试 return 来自函数的值,其中 return 值位于 then() 块内。 赛普拉斯抛出一堆错误,我正在混合异步和同步代码。我尝试了 returning 一个 Promise 并解决了它,但这也引发了错误。

cy.get('.btn.btn-primary')
  .each(function ($el, index, $list) {
    // Lot of code
 
    if (price < minPrice) minPrice = price
  })
  .then(() => {
    cy.log(minPrice); //This works fine
    return minPrice; //This throws ERROR
  })

您可以使用别名来保存该值,然后像这样使用它。

cy.get('.btn.btn-primary')
  .each(function ($el, index, $list) {
    // Lot of code

    if (price < minPrice) minPrice = price
  })
  .then(() => {
    cy.log(minPrice) //This works fine
    cy.wrap(minPrice).as('minPrice') //Saved as alias
  })

//In your test you can use it as
cy.get('@minPrice').then((minPrice) => {
  //Access minPrice here
  cy.log(minPrice) //prints minPrice
})