I have a directive that initializes the Date object several times in several functions.
When Unit testing the individual functions I can handle stubbing the date like this:
(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);
});
For unittesting the directive itself, which calls the ageInYears and several other similar functions this isn't going to work as I after one call to Date() stubDateConstructor will have reset Date() to the real Date object.
Is there a native way in AngularJS / Jasmine to handle these situations, or should I look into Sinon e.g.?
question from:
https://stackoverflow.com/questions/17086320/mocking-dates-in-angularjs-jasmine-tests 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…