Home > Enterprise >  In JavaScript, retrieve the value and performed the addition after that want to return the value aft
In JavaScript, retrieve the value and performed the addition after that want to return the value aft

Time:05-12

verifyActiveInterfacesViaConnectionStatus() {
        var sum = 0
        var i;
        for (i = 1; i <= 5; i  ) {
            cy.xpath(`(//*[name()='g' and @class ='highcharts-label highcharts-data-label highcharts-data-label-color-undefined']//*[name()='text']//*[@class='highcharts-text-outline'])[${i}]`).invoke("text").then(($text1) => {

               var textValue1 = $text1   "\n"
               cy.log(textValue1)
               var  total = parseInt(textValue1)
               sum  = total
            })
        }
        cy.log("Total of all connected OS= "   sum)
    }

In the cypress automation, when I'm running this block of code it is returning the sum=0 but I don't know why it is displaying 0. Please help me out.

CodePudding user response:

Cypress behaves weirdly when running inside of a for loop. When Cypress commands are executed vs. just regular JavaScript is not readily apparent without really diving into the inner workings of Cypress. A more reliable way to get Cypress to behave as expected would be to use Cypress Lodash (it is essentially a Cypress wrapper around Lodash).

let sum = 0
Cypress._.times(6, (i) => {
  // lodash times gives us the index of the current iteration as the parameter in the callback
  // this can be used the same as the `i` in your for loop.
  // code to execute
});

CodePudding user response:

Cypress commands are asynchronous. cy.log captures the sum value before the first xpath command gets really executed. To synchronize access to the sum you can use a then callback:

verifyActiveInterfacesViaConnectionStatus() {
        var sum = 0
        var i;
        for (i = 1; i <= 5; i  ) {
            cy.xpath(`(//*[name()='g' and @class ='highcharts-label highcharts-data-label highcharts-data-label-color-undefined']//*[name()='text']//*[@class='highcharts-text-outline'])[${i}]`).invoke("text").then(($text1) => {

               var textValue1 = $text1   "\n"
               cy.log(textValue1)
               var  total = parseInt(textValue1)
               sum  = total
            })
        }
        cy.then(() => {
           cy.log("Total of all connected OS= "   sum)
        })
    }
  • Related