Is it possible to extract the value in JavaScript, add it, and then return the result after a for loop in Cypress automation?

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

               var textResult = $textValue + "\n"
               cy.log(textResult)
               var  value = parseInt(textResult)
               totalSum += value
            })
        }
        cy.log("Total sum of connected interfaces= " + totalSum)
    }

When executing this code in cypress automation, I am getting a sum of 0. I am unsure why it is returning 0. Kindly provide assistance.

Answer №1

One interesting aspect of Cypress commands is that they are asynchronous. When you use the cy.log command, it captures the value of sum before the first xpath command actually executes. To ensure synchronized access to the sum, you can utilize 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)
        })
    }

For more in-depth information on how to handle variables within Cypress, take a look at this article.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scraping data using Selenium with paragraph tags

I've been scouring the internet for examples similar to the one in question, but with no luck. The challenge at hand revolves around extracting text from a webpage where only one of two p tags contains important information. How can data be extracted ...

Selenium in Python fails to locate an element (empty result returned)

My Python code snippet is below: elements=driver.find_elements_by_id("folder_c0fb056b-f83a-495e-9db1-dd1b19942eaa") print(elements) After running the code, the result returned as [ ]. This approach has worked successfully for other sections of the websit ...

Leverage selenium to enter data for numerous elements by utilizing xpath

I am new to using Selenium and I am exploring ways to locate a series of input elements using xpath or css. My goal is to iterate over each element and input text into them. For example: <form> value1 <input type="text" placeholder="value1"> ...

Is there a method to review all the details of a button on a website once Selenium has identified that specific element?

Could I potentially analyze the attributes of a button element that I have selected using selenium? I am currently utilizing selenium to navigate through complex JavaScript-based web pages. My goal is to download certain files from these pages, but before ...

Ways to Verify the Absence of a Web Element on a Page

When an action button is clicked, it can produce one of two outcomes depending on the input condition. If invalid data is provided, a validation error will be displayed in the message table. However, if valid data is entered, the message table will not be ...

Listening with TestNG

In my project, I have implemented a listener class. Upon researching online, I discovered that there are two different methods for adding a listener - either to your class or to the TestNG file. Take a look at the folder structure. Currently, I am incorpo ...

Tips on entering data into a span element with Selenium?

<div data-offset-key="hch7-0-0" class="_1mf _1mj"><span data-offset- key="hch7-0-0"><br data- text="true"></span></div> <span data-offset-key="hch7-0-0"><br ...

What is the best way to extract data from various webpages connected to a single source using selenium?

Lately, I've been working on extracting a large amount of pricing data from a website by starting with one page that contains links to each item's individual page. My goal was to automate the process using a script that would click on a specific ...

Javascript and Agile Development: A Perfect Match

I am interested in implementing Agile Development for a project that uses web2py on the backend and Ember on the frontend. To achieve this, I would like to incorporate Behavior Driven Development (BDD) tools such as Cucumber and Capybara for Rails. It is i ...

Is it possible to integrate a selenium driver with Quarkus?

It has come to my understanding that Selenium is typically implemented in Java, while Quarkus is a lighter version of Java that avoids heavy reliance on reflection. However, I have been unable to find any information about someone successfully launching a ...

Encountered difficulties launching asp.net application with Selenium WebDriver on IIS

My application is built in ASP.NET and I utilize the Selenium WebDriver library. When running my program in Visual Studio, it launches the Express IIS server and opens my Selenium application correctly. However, when I try to host it on an IIS server outsi ...

Ruby/Selenium WebDriver - Implementing a pause in the test for user interaction, such as requiring input for a captcha prompt

While using Selenium WebDriver and Ruby for automation, I encountered a captcha issue during step 3 of a 5-step process. I have all the automation set up in a rake script, so I'm looking for a way to temporarily pause or break the script until I can ...

Hunt down content using Selenium without relying on an ID or Name

Looking to locate specific text within HTML code using Selenium and Python. The desired text only appears after meeting certain conditions (successful file upload). See excerpt of HTML code below, with full code available in the provided link. The sought- ...

Steps to extract information from a WebElement

While in debugging mode, I noticed that the locator for a particular element on the page is shown as: By.name: NameOfMyElement_123. Now, my query is how can I extract and parse the string (By.name: NameOfMyElement_123) using Java to identify the type of t ...

Guide to launching Chrome Developer Tools in Selenium WebDriver with JAVA

I am seeking advice on how to open the Chrome developer Console while running selenium tests. Whenever I try to manually open the console by pressing F12 during test execution, the tests become unresponsive and eventually fail. Does anyone know how I can ...

Grabbing Checkbox Labels Using Selenium WebDriver

Hello, I am currently attempting to retrieve the name located next to the checkbox within the same span class. The name is contained within the label tag. Unfortunately, when using the getText() method, I am receiving an empty name. Below is how I am atte ...

How can I include the paths for "testng.xml" and log4j2.xml in my pom.xml file for a Selenium - Maven/TestNG project, ensuring the executable .jar file can run on any machine?

I am currently utilizing Maven, TestNG, and Log4j2 in my project. Our goal is to generate an executable .jar file that will execute testng.xml via the pom.xml file. As of now, I have successfully created an executable .jar file and ran it without any iss ...

Tips for using Selenium to interact with the save or print button in the Google Chrome print window, even when the HTML page contains a shadow-root

https://i.stack.imgur.com/NFJat.pngMy goal is to use Selenium and Python for web scraping. I am currently using Chrome version 123.0.6312.87 with a compatible web driver. Specifically, I am interested in extracting data from the following page: "https://we ...

Is there a way to confirm that the results are organized correctly in Selenium IDE, for example, in alphabetical order or descending by ID?

Recently delving into the world of Selenium IDE, I find myself in need of verifying the correct order of a list. This list is populated with records pulled from a database. While I understand I can create two unique records with given values and utilize me ...

Error Encountered in Protractor: SyntaxError - An unexpected token '=' was found

It seems like my webdriver scripts have suddenly stopped working. This is the code that was previously functioning: var loginPageObject = require ('./pageObjects/00_login_page.po.js'); describe('log in to app', function() { it(&apo ...