Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
How to access a variable which is updated inside the function in outer scope in Cypress/Javascript?

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
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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
  })
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda