1

Here is the problem statement. I am trying to find all items on a webpage and find the item with the minimum price using Cypress. The problem is, as long as I am inside the inner function, minPrice is correct. However when I try to print minPrice in the outer function, minPrice again gets assigned to it outer scope value. I am fairly new to JS, so looks like I am missing some basic JS concept here. I tried a lot of things like variable scoping, async/await (which cypress claims it doesnt need), but no success. Please help!

Below is the code.

getMinPrice(){
//Initialize to a very big number
  var minPrice = 10000;
 
  cy.get('.btn.btn-primary').each(function ($el, index,$list) {

    //For each element, do some parsing to get the price for the item
    var textToParse = $el.attr('onclick');
    var price = textToParse.slice(-4,-1);
    price = parseInt(price,10);
    
   //compare price with current MinPrice
   if (price < minPrice)
          minPrice = price; 
  });
 
  cy.log(minPrice); // Logs 10000 which is not what I am expecting
}
  • this will be helpful: https://docs.cypress.io/guides/core-concepts/introduction-to-cypress#Using-then-To-Act-On-A-Subject – Randy Casburn Nov 30 '21 at 14:25
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Randy Casburn Nov 30 '21 at 14:25
  • 1
    Thanks for your response. @alapan below solved it for me. Will go thru the docs in detail – Pavan Kulkarni Nov 30 '21 at 15:42

1 Answers1

1

It is because JS works asynchronously your log statement is running before the value of minPrice is updated. To make sure that the log has the updated minprice, we can use then to make sure the log statement is run only after each has finished executing.

cy.get('.btn.btn-primary')
  .each(function ($el, index, $list) {
    //For each element, do some parsing to get the price for the item
    var textToParse = $el.attr('onclick')
    var price = textToParse.slice(-4, -1)
    price = parseInt(price, 10)

    //compare price with current MinPrice
    if (price < minPrice) minPrice = price
  })
  .then(() => {
    cy.log(minPrice) //should have the updated value
  })
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • Thanks a lot! That totally makes sense. – Pavan Kulkarni Nov 30 '21 at 14:50
  • Follow up question here. I am trying to return the minPrice to the calling function but Cypress throws a bunch of errors for mixing sync code with async code. How to tackle this? I tried chaining another "then" but didn't help. – Pavan Kulkarni Nov 30 '21 at 16:03
  • I will suggest you to create a separate question for this as this goes beyond the scope of this question. – Alapan Das Nov 30 '21 at 16:13