[英]Unit testing with Mocha and Momentjs
我有我試圖與摩卡單元測試使用的功能moment
。
function makeRange(timeagoMinutes) {
var endDate = moment().toISOString();
var startDate = moment().subtract(timeagoMinutes, 'm').toISOString();
return startDate + ',' + endDate;
}
這里是我到目前為止,但我有麻煩搞清楚是做什么用moment
。 如果我調用makeRange(40)
並運行測試,則字符串每次都不同。
如何偽造當前時間(即moment().toISOString()
?
var rewire = require('rewire');
var controller = rewire('../thecontroller.js');
var moment = require('moment');
describe.only('makeRange', function() {
var makeRange;
beforeEach(function() {
makeRange = controller.__get__('makeRange');
});
it('should return a string with a start date and end date', function() {
//
});
});
您正在使用rewire
,因此可以模擬控制器中所需的moment
模塊,以確保使用了已知的日期/時間:
describe.only('makeRange', function () {
var makeRange;
beforeEach(function () {
var momentMock = function () {
return moment('2016-08-31T09:00:00Z');
};
controller.__set__("moment", momentMock);
makeRange = controller.__get__("makeRange");
});
it('should return a string with a start date and end date', function () {
expect(makeRange(40)).to.equal('2016-08-31T08:20:00.000Z,2016-08-31T09:00:00.000Z');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.