问题描述
我正在使用moment.js在React组件的帮助器文件中执行大多数日期逻辑,但是我还无法弄清楚如何在Jest a la sinon.useFakeTimers()中模拟日期.
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().
Jest文档仅谈论setTimeout,setInveral等计时器函数,但无助于设置日期,然后检查我的date函数是否完成了它们打算做的事情.
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.
这是我的一些JS文件:
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;
这是我使用Jest设置的内容:
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?
推荐答案
MockDate 可用于开玩笑的测试中进行更改new Date()
返回什么:
MockDate can be used in jest tests to change what new Date()
returns:
var MockDate = require('mockdate');
// I use a timestamp to make sure the date stays fixed to the ms
MockDate.set(1434319925275);
// test code here
// reset to native Date()
MockDate.reset();
这篇关于如何在Jest中设置模拟日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!