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?
To test sorting in any order,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With