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
}
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
})