Protractor: testing date text with various formats

Problem

HTML:

<div id="date"> {{date | date : 'EEE MMM d HH:mm'}} </div>

It displays on the screen at "Tue Sep 30 10:45"

Test:

expect(element(by.id('date')).getText()).toBe("Tue Sept 30 10:45");

Fails with:

Expected 'Sep 30, 2014 10:45' to be 'Tue Sep 30 10:45'.

Problem courtesy of: Jason

Solution

I think you need to compare Date objects, not strings:

element(by.id('date')).getText().then(function (value) {
    var dateValue = new Date(value);
    var expectedDateValue = new Date(dateValue.getFullYear(), 9, 30, 10, 45, 0);

    expect(dateValue).toBe(expectedDateValue);
});

If you want to additionally check the format, you can dive into the wonderful world of regular expressions, or just use the moment.js library:

element(by.id('date')).getText().then(function (value) {
    expect(moment(value, ["EEE MMM d HH:mm"]).isValid()).toBe(true);
}
Solution courtesy of: alecxe

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.