【发布时间】:2013-06-09 19:04:00
【问题描述】:
我有一个指令在几个函数中多次初始化 Date 对象。 当对单个函数进行单元测试时,我可以像这样处理存根日期:
(function (global) {
var NativeDate = global.Date;
global.stubDateConstructor = function (fakeDate) {
global.Date = function () {
global.Date = NativeDate;
return fakeDate;
}
}
}(this));
// ageInYears()
it("should return the age in years of the person given his/her birthdate", function() {
stubDateConstructor(new Date('2010/01/01'));
expect(ageInYears('01-01-1990')).toBe(20);
stubDateConstructor(new Date('2010/01/01'));
expect(ageInYears('01-01-1900')).toBe(110);
});
为了对指令本身进行单元测试,它调用ageInYears 和其他几个类似的函数,因为我在一次调用Date() stubDateConstructor 后会将Date() 重置为真正的Date 对象。
AngularJS / Jasmine 中是否有本地方式来处理这些情况,或者我应该研究一下 Sinon,例如?
【问题讨论】:
-
现在我开始意识到我可能必须初始化一次 date 并将其传递给需要它的函数..也许这是最好的解决方案?
-
我自己是 Timecop.js 的粉丝。任何具有 Timecop.travel 和 Timecop.freeze 等功能的库都会得到我的认可。
-
看起来 sinon.js 还可能提供适用于日期的时间模拟(取决于浏览器支持)sinonjs.org/docs/#clock
标签: unit-testing date angularjs