0

I want to get all values from a column in the table on webpage until the column does not contain an element, sum values and return the sum as a promise.

   TablePage.prototype.getPriceValuesFromList = function () {
      for (number = 1; number < 100; number++) {
          var locator = '//*[@id="root"]/main/section/table/tbody/tr[' + number + ']/td[3]/div[2]';
            browser.findElement(By.xpath(locator)).then(function (success) {
            if (success) {
                var locator = '//*[@id="root"]/main/section/table/tbody/tr[' + number + ']/td[3]/div[2]';
                return element(By.xpath(locator)).getText().then(function (text) {
                    numb = text.replace(/,/g, '');
                    numb = numb.replace(/\$/g, '');
                    numb = numb.replace(/\./g, '');
                    prices[number] = parseInt(numb);
                    console.log(prices[number]);
                    var sum = prices.reduce(function(a, b) { return a + b; }, 0);
                    console.log(sum);
                    return sum
                })
            }
            else {
                break;
                }
            })
      }
    };

I get : "Illegal break statement"

How to actually do it?

Do I have to define "locator" 2 times?

jedrek cienicki
  • 153
  • 1
  • 14
  • You're trying to break sync loop from async callback. ([findElement](https://www.protractortest.org/#/api?view=ProtractorBrowser.prototype.findElement) returns promise that would be resolved to WebElement, so propably you can call `getText()` on `success` ) Can't you create path that excludes those rows with elements, sum? (for example by class) – barbsan Sep 21 '18 at 10:36
  • no it's not possible, i can do it only by xpath. How to make for loop iterate in both promises and break in the second? – jedrek cienicki Sep 21 '18 at 11:08
  • I meant to include information about class in xpath [like here](https://stackoverflow.com/questions/1604471/how-can-i-find-an-element-by-css-class-with-xpath) – barbsan Sep 21 '18 at 11:20
  • class is the same for all rows in the table and i want only one column, i can make xpath relative but it probably won't solve the issue – jedrek cienicki Sep 21 '18 at 11:26
  • 1
    Show the HTML code of the table – yong Sep 21 '18 at 13:35
  • it's this app https://budget.modus.app/budget – jedrek cienicki Sep 21 '18 at 14:11

1 Answers1

0

You can use element.all() to find all td of the 3rd column, then use map() to convert each text value of td to an Number.

TablePage.prototype.getPrice2List = function(){

    return element
        .all(by.css('#root table tbody tr > td:nth-child(3)'))
        .map(function(item){
            // replace all non-numeric,non-dot, not-dash to ''
            return Number(item.replace(/[^\d\.-]/g, '').trim());
        });
};

tablePage.getPrice2List().then(function(prices){
    console.dir(prices);
})
yong
  • 13,357
  • 1
  • 16
  • 27