Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below).

My task involves extracting all number values listed under the Revenue header and conducting a summation operation. However, I am encountering difficulties in retrieving all the values using a loop or ng-repeat. Below is a visualization of the structure of my DOM:

Included are 89 td/tr tags within the tbody, as per the illustration above.

I am seeking guidance on devising a logic to effectively fetch all values from the tbody and execute SUM operations on them. Any assistance would be greatly appreciated!

Answer №1

This code snippet will help you achieve your desired outcome:

function calculateSumInColumn(tableID, columnNumber, expectedResult){
    var cellsToSum = element.all(by.css('#'+tableID+' tr td:nth-of-type(2)'));
    var currentSum = 0;
    cellsToSum.each((cell) => {
        cell.getText().then((text) => {                            
            currentSum += Number(text);
        });
    }).then(() => {
        expect(currentSum.toString()).toEqual(expectedResult);
    });
}//END OF calculateSumInColumn

Let's break down the implementation step by step:

In this part of the code, you are selecting all the cells in a specific column of a table. Replace the variable tableID with the ID (or any other CSS selector) of your table. The 'nth-of-type(2)' corresponds to the column number, so if you want to make it dynamic based on a parameter, you can modify the code as follows:

var cellsToSum = element.all(by.css('#'+tableID+' tr td:nth-of-type('+columnNumber+')'));

Now, the cellsToSum array contains all the numerical values as strings.

In the next section, you iterate through each cell, extract its text content, convert it to a number, and perform the summation: *Before converting to a number, ensure that the string contains only numeric characters.

    cellsToSum.each((cell) => {
        cell.getText().then((text) => {                            
            currentSum += Number(text);
        });
    })

Finally, the last part handles the promise sequence where you can use the currentSum variable to compare with the expected result or execute any other operation accordingly.

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

Create a search feature based on names utilizing Node Express in conjunction with SQL database

After deciding to create an API with a search feature using SQL queries in node express, this is how I structured my code: app.get('/search/:query', (req, res) => { pool.getConnection((err, connection) => { if(err) throw err ...

The installation of robotjs via npm failed due to issues encountered while trying to build the binaries

After attempting to execute the command "npm install robotjs -g," an error is thrown back at me. [email protected] install C:\Users\Ehsan\AppData\Roaming\npm\node_modules\robotjs prebuild-install || node-gyp reb ...

Angular Form Validation: Ensuring Data Accuracy

Utilizing angular reactive form to create distance input fields with two boxes labeled as From and To. HTML: <form [formGroup]="form"> <button (click)="addRow()">Add</button> <div formArrayName="distance"> <div *n ...

The website functions properly in Chrome, but encounters issues in IE

Currently working on validating some JavaScript code. Chrome seems to be handling it well, but as expected, IE is causing some issues. Take a look at the code below: function validateData(a,id){ var inputs = document.getElementsByName('attname[] ...

The function Document.getElementsByName() behaves differently in Internet Explorer, returning an object, compared to Chrome where it returns

While trying to meet my requirements, I encountered a discrepancy between running the page in IE browser versus Chrome. The code worked successfully in IE, but not in Chrome. for(var gridNo=0;gridNo < 30;gridNo++){ var fldId = arry[0]+'_& ...

Exploring the depths of design in material-ui

I've just started diving into material-ui and decided to create a simple app in the SandBox: https://codesandbox.io/s/eager-ride-cmkrc The styling using jss is a bit unusual for me, but with your help on these two exercises, I'm sure I'll ...

Troubleshooting VueJS route naming issues

I am having an issue with named routes in my Vue app. Strangely, the same setup is working perfectly fine in another Vue project. When I click on a named router-link, the section just disappears. Upon inspecting the element in the browser, I noticed there ...

Changing the .load function based on user input

Can I replace a .load text with one that can be updated by a user using form input or similar method? My goal is to create a code that retrieves data using unique div IDs (specific to each employee) containing information within tables across various HTML ...

Does vite handle module imports differently during development versus production?

I am currently working on incorporating the jointjs library into a Vue application. It is being declared as a global property in Vue and then modified accordingly. Below is a basic example of what I am trying to achieve: import Vue from 'vue'; im ...

I am having trouble scrolling through the main content when the side-drawer is open. How can I fix this issue?

When the sidebar is opened, I am facing issues with the main content scroll and certain fields such as select options and search bar not functioning properly. I have included the main content in the routes from which it is being loaded. However, the scroll ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

The absence of the iframe in ie8 is causing problems that cannot be fixed with relative positioning

On a website, I am integrating an external 2-factor authentication solution called Duo Web using their PHP and Javascript. It works smoothly on all browsers except for IE8. When the user passes the initial login screen, the 2FA login page loads, but the if ...

Using Linux variables in the .env file of your Vue.js project can provide a convenient way to

Using .env in a *.js file allowed me to set the BANK variable as either A_BANK or B_BANK like so: BANK=A_BANK or BANK=B_BANK However, when passing the argument as A_BANK or B_BANK like: --bank A_BANK in a shell script loop for var in $@ do if [ ${var} ...

How to pass data/props to a dynamic page in NextJS?

Currently, I am facing a challenge in my NextJS project where I am struggling to pass data into dynamically generated pages. In this application, I fetch data from an Amazon S3 bucket and then map it. The fetching process works flawlessly, generating a se ...

Step-by-step guide on activating a button only when all form fields are validated

My very first Angular 5 project. I've gone through resources like: https://angular.io/guide/form-validation and various search results I looked up, only to realize that they are all outdated. In my form, I have several input fields such as: <for ...

Maximizing the power of Webpack alongside Google Maps API

I have been using Webpack along with the html-webpack-plugin to compile all my static files. However, I am facing an issue when integrating it with the Google Maps API. Here is the code snippet: var map; function initMap() { map = new google.maps.Map(d ...

I'm experiencing an issue where using .innerHTML works when viewing the file locally, but not when served from a web server. What could be causing this discrepancy?

Utilizing mootool's Request.JSON to fetch tweets from Twitter results in a strange issue for me. When I run the code locally as a file (file:// is in the URL), my formatted tweets appear on the webpage just fine. However, when I serve this from my loc ...

Conceal the scroll bar while the page preloader is active

Is there a way to hide the scroll bar while the preloader is loading on a webpage? I want to prevent users from scrolling until the preloader disappears. I have tried using CSS and setting the body overflow to hidden, but it's not working as expected. ...

The requested page for angular-in-memory-web-api could not be located within the Angular 4.2.2 CLI web-api functionality

Currently, I am delving into the Angular framework (specifically version 4.2.2) and going through the Tour of Heroes tutorial. As I progressed to the HTTP section, the tutorial introduced the use of angular-in-memory-web-api to simulate a web api server. ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...