Search code examples
javascriptangularjstestingprotractorend-to-end

Protractor: Checking data is sorted by date


I need to check the data returned is sorted by date. This is how I'm writing it:

it('should be sorted by date', function() {
    element.all(by.repeater('users in group.users')).then(
        function(users) {
            var lastUser = users[0].element(by.id('birth-date')).getText();
            for (var i = 1; i < users.length; ++i) {
                var currentUser = users[i].element(by.id('birth-date')).getText();
                expect(moment(currentApplication).format('MMM d, YYYY HH:mm')).toBeGreaterThan(moment(lastApplication).format('MMM d, YYYY HH:mm'));
                lastUser = currentUser;
            }
        }
    )
})

This returns:

Expected 'Jan 1, 2015 00:00' to be greater than 'Jan 1, 2015 00:00'.

What am I doing wrong? currentUser and lastUser seem to be objects instead of text...but I'm not sure why.


Solution

  • Get the list of all birth dates using map(), convert the list of strings to the list of dates and compare with a sorted version of the same array:

    element.all(by.id('birth-date')).map(function (elm) {
        return elm.getText().then(function (text) {
            return new Date(text);
        });
    }).then(function (birthDates) {
        // get a copy of the array and sort it by date (reversed)
        var sortedBirthDates = birthDates.slice();
        sortedBirthDates = sortedBirthDates.sort(function(date1, date2) {
            return date2.getTime() - date1.getTime()
        });
    
        expect(birthDates).toEqual(sortedBirthDates);
    });