我有一个指令,它在几个函数中多次初始化 Date 对象。
当对单个函数进行单元测试时,我可以像这样处理 stub 日期:
(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,例如?
最佳答案
Jasmine (2.2) Clock 可以模拟日期和时间。
http://jasmine.github.io/2.2/introduction.html#section-Mocking_the_Date
例如(来自文档):
it("mocks the Date object and sets it to a given time", function() {
var baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
jasmine.clock().tick(50);
expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
});
关于unit-testing - AngularJS/Jasmine 测试中的模拟日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17086320/