I'm using moment.js to handle dates from JavaScript and Jasmine to write unit tests. At a given moment I want to do a test that checks that two dates are the same, for which I do the following:
it('properly compares dates', function () {
var date1 = moment("2000-01-02", "YYYY-MM-DD");
var date2 = moment("1999-03-04", "YYYY-MM-DD");
expect(date1).toEqual(date2);
});
This works as expected: if the dates were the same, the test would pass, but since they are not, it does not pass. The problem : the error message it throws contains the entire object, from which it is very difficult to extract the compared values:
Expected Moment({ _isAMomentObject: true, _i: '2000-01-02', _f: 'YYYY-MM-DD', _isUTC: false, _pf: Object({ empty: false, unusedTokens: [ ], unusedInput: [ ] , overflow: -1, charsLeftOver: 0, nullInput: false, invalidMonth: null, invalidFormat: false, userInvalidated: false, iso: false }), _locale: Locale({ _ordinalParse: /\d{1,2}(th| st|nd|rd)/, ordinal: Function, _abbr: 'in', _ordinalParseLenient: /\d{1,2}(th|st|nd|rd)|\d{1,2}/ }), _d : Date(Sun Jan 02 2000 00:00:00 GMT+0100 (Romance Standard Time)) }) to equal Moment({ _isAMomentObject: true, _i: '1999-03-04', _f: 'YYYY-MM-DD ', _isUTC: false, _pf: Object({ empty: false, unusedTokens: [ ], unusedInput: [ ], overflow: -1, charsLeftOver: 0, nullInput: false, invalidMonth: null, invalidFormat: false, userInvalidated: false, iso: false }),_locale: Locale({ _ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: Function, _abbr: 'en', _ordinalParseLenient: /\d{1,2}(th|st |nd|rd)|\d{1,2}/ }), _d: Date(Thu Mar 04 1999 00:00:00 GMT+0100 (Romance Standard Time)) })
My question is: is there a way to customize the error messages for failed tests in Jasmine (specifically for moment.js)? I haven't been able to find any solution in the official documentation.
I ended up implementing a custom matcher that I register before the tests:
So, simply substituting
.toEqual
for.toBeSameDate
in the test, the error message changes to:This also has the advantage that in the future I can extend the matcher if necessary, for example to ignore the time.
You can do it by comparing the formatted date, using
moment.format()
:This allows you to check a date and if the test fails, see a compact and complete detail.
http://jsfiddle.net/rnrlabs/w5duncaL/