How to get values from a grid and perform sum operation in PROTRACTOR

615 Views Asked by At

I am completely new to Protractor and Javascript. I am trying to write a test script which can fetch the values of some accounts under a header "Revenue" (Image below)

Revenue Header

I need to fetch all the number values populated under the Revenue header and do a "SUM" operation. The problem is, I am not able to fetch all the values using a loop or ng-repeat. The below is how my DOM looks like: Revenue DOM

I have some 89 td/tr tags under the tbody like shown in the above picture.

Could someone help me with the logic of how can I fetch all the values using the tbody and perform a SUM operations for the fetched values?

1

There are 1 best solutions below

0
On

With this you will have what you want:

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

So, I will explain row by row

in this row you are capturing all the column values from the table and the specific column. Replace the var tableID with the id (or other css selector) of your table the code part 'nth-of-type(2)' is about the columns, so in your case is number 2 for the second column... you can make something like this to make it possible to receive the value from the function's parameter:

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

So now the var expectedCells has an array of all the numbers (as string)

In this part you are getting the array, getting the text of each position, transforming in Numeric and performing the math operation you want (sum): *In your case, work the string before you make the conversion to Numeric, make sure you are sending only numbers

    expectedCells.each((eachCell) => {
        eachCell.getText().then((cellText) => {                            
            currentSum += Number(cellText);
        });
    })

The last part its the sequence of the promise that will allow you to use the var currentSum and compare with the expected value (or simply do something else)