1
votes

how to check the table data is sorted or not in protractor js

it('check for the presence of Transactions grid',function(){ // browser.sleep(20000); element(by.css('[ng-click="toggleSelection(\'backtest\',\'transactions\', portfolio)"]')).click(); browser.sleep(5000);

    var items = element.all(by.repeater('stock in tableData.none'));

    element(by.xpath('//*[@id="collapse0"]/div[3]/div[2]/div/div[4]/div[1]/div[2]/div[3]/a')).click();
    browser.sleep(50000);

    var unsorted = items.map(function(element) {
        return element.getText();
      });
      // console.log(unsorted);
      var sorted = unsorted.then(function(texts) {

        // Make sure to copy the array to not sort the original
        return texts.slice(0).sort();
      });

      var equals = protractor.promise.all([unsorted, sorted]).then(function(texts) {
        var unsorted = texts[0];
        var sorted = texts[1];
        var allEqual = (unsorted.length === sorted.length);
        sorted.forEach(function(sortedItem, i) {
          allEqual = allEqual && (sortedItem === unsorted[i]);
        });
        return allEqual;
      });

      expect(equals).toBe(true);
  });

how to check the table data is sorted or not

1

1 Answers

1
votes

I happened to have the same requirement recently. The idea is to

  • Read each column data using appropriate xpath/css-selector into an array
  • Test if that array is sorted

Here is the working sample code i had used. It assumes that the table is sorted in Ascending manner but should be easy to do the other way as well.

Table:

<table class="sortedElements">
    <thead>
        <tr>
            <th>Number</th>
            <th>String</th>
        </tr>
    </thead>
    <tbody>
        <tr><td>1</td><td>aaa</td></tr>
        <tr><td>2</td><td>aab</td></tr>
        ... sorted data in both tds goes on ...
    </tbody>
</table>

Spec test (integers):

var integers = [];
var allIntegers = element.all(by.css('.sortedElements > tbody > tr > td:nth-child(1)'));
allIntegers.each((td) => {
    td.getText().then((val) => {
        integers.push(val)
    })
}).then(() => {
    expect(integers.every((val, i) => (i < integers.length - 1 ? parseInt(val) <= parseInt(integers[i + 1]) : true)) === true).toBeTruthy();
});

Spec test (strings):

var strings = [];
var allStringsTds = element.all(by.css('.sortedElements > tbody > tr > td:nth-child(2)'));
allStringsTds.each((td) => {
    td.getText().then((val) => {
        strings.push(val)
    })
}).then(() => {
    expect(strings.every((val, i) => (i < strings.length - 1 ? val <= strings[i + 1] : true)) === true).toBeTruthy();
});

Hope that helps..