簡體   English   中英

從賽普拉斯的異步塊返回一個值?

[英]Return a value from an async block in Cypress?

我正在嘗試從 function 返回一個值,其中返回值位於 then() 塊內。 賽普拉斯拋出了一堆錯誤,我正在混合異步和同步代碼。 我嘗試返回 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
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM