I'm using moment.js to do most of my date logic in a helper file for my React components but I haven't been able to figure out how to mock a date in Jest a la sinon.useFakeTimers().
The Jest docs only speak about timer functions like setTimeout, setInveral etc but don't help with setting a date and then checking that my date functions do what they're meant to do.
Here is some of my JS file:
var moment = require('moment');
var DateHelper = {
DATE_FORMAT: 'MMMM D',
API_DATE_FORMAT: 'YYYY-MM-DD',
formatDate: function(date) {
return date.format(this.DATE_FORMAT);
},
isDateToday: function(date) {
return this.formatDate(date) === this.formatDate(moment());
}
};
module.exports = DateHelper;
and here is what I've set up using Jest:
jest.dontMock('../../../dashboard/calendar/date-helper')
.dontMock('moment');
describe('DateHelper', function() {
var DateHelper = require('../../../dashboard/calendar/date-helper'),
moment = require('moment'),
DATE_FORMAT = 'MMMM D';
describe('formatDate', function() {
it('should return the date formatted as DATE_FORMAT', function() {
var unformattedDate = moment('2014-05-12T00:00:00.000Z'),
formattedDate = DateHelper.formatDate(unformattedDate);
expect(formattedDate).toEqual('May 12');
});
});
describe('isDateToday', function() {
it('should return true if the passed in date is today', function() {
var today = moment();
expect(DateHelper.isDateToday(today)).toEqual(true);
});
});
});
Now these tests pass because I'm using moment and my functions use moment but it seems a bit unstable and I would like to set the date to a fixed time for the tests.
Any idea on how that could be accomplished?
Since momentjs uses
Date
internally, you can just overwrite theDate.now
function to always return the same moment.or
jest-date-mock is a complete javascript module wrote by me, and it is used to test Date on jest.
Use the only 3 api for test cases.
MockDate can be used in jest tests to change what
new Date()
returns:For those who want to mock methods on a new Date object you can do the following:
Goal is to mock new Date() with a fixed date wherever it's used during the component rendering for test purposes. Using libraries will be a overhead if the only thing you want is to mock new Date() fn.
Idea is to store the global date to a temp variable, mock the global dae and then after usage reassign temp to global date.
I just wanted to chime in here since no answer addressed the issue if you want to mock the
Date
object in only a specific suite.You can mock it using the setup and teardown methods for each suite, jest docs
Hope this helps!