Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protractor e2e testing for sorting

I am writing e2e test cases using protractor. I am trying to write tests for sorting (ascending, descending). This is my html code

<tbody>
    <tr>
        <td>
         <a ng-click="sortBy('Name')" href="" style="text-decoration: none;" class=""> Name</a>
        </td>
        <td>
         <a ng-click="sortBy('RollNo')" href="" style="text-decoration: none;"> Roll Number</a>
        </td>
        <td>
         <a ng-click="sortBy('subject')" href="" style="text-decoration: none;"> Subject</a>
        </td>     
    </tr>
    <tr>
        <td>ANDREW, STRAUSS</td>
        <td>122</td>
        <td>Maths</td>
    </tr>  
    <tr>
        <td>ANDREW, STRAUSS</td>
        <td>123</td>
        <td>Science</td>
    </tr>      
</tbody>

Can we test sorting. If yes, how?

like image 708
Nagarjuna Reddy Avatar asked Sep 01 '15 11:09

Nagarjuna Reddy


1 Answers

To test sorting in any order,

  • Click on the sortBy element so that element's get sorted in an order.
  • Get the element's text from the columns displayed with a sort order.
  • Later store each element's text in an array so that you can check for sorting later.
  • Next step is to copy this unsorted array into a temporary array and sort the temporary array.
  • Last thing is to check if the element is sorted in the order you need, which you can verify using expect statement.

Use Javascript sort() method to check sorting in ascending order and reverse() to check sorting in descending order.

You can test sorting of elements in ascending order by adding them in an array and then verify it with the sorted array. Here's a sample on how to do it -

var sorted = [] , unSorted = [];
var ele = element.all(by.css(tbody tr td:nth-of-type(1)));
ele.each(function(eachName){
    eachName.getText().then(function(name){
        unSorted[i] = name;
        i++;
    });
}).then(function(){
    //check sorting
    sorted = unSorted.slice();
    sorted.sort(); //use sort function of Javascript
    expect(sorted).toEqual(unSorted);
});

Similarly you can try with other elements to check for other types of sorting in your case sort by RollNo and subject. If you are facing issues with async errors as protractor is fast, then you can chain your sorting verification code with the loop.

Another method is to use map() function of protractor to get all elements text into an array and then check for sorting. I recommend using this. Here's an example -

    ele.map(function(eachName){
        return eachName.getText().then(function(unSorted){
            return unSorted;
        });
    }).then(function(unSorted){
            var sorted = unSorted.slice();
            sorted = sorted.sort(); //sort the array
            expect(sorted).toEqual(unSorted); //check if both sorted and unsorted arrays are same
    });

Hope this helps.

like image 134
giri-sh Avatar answered Sep 20 '22 09:09

giri-sh