Search code examples
seleniumselenium-webdriverautomated-testscypresscypress-component-test-runner

In JavaScript, retrieve the value and performed the addition after that want to return the value after the for loop in cypress automation?


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.


Solution

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

    Look at this article for details on how to handle variables at Cypress.