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:
I was able to mock using a combination of sinon's fake timers to mock the window's timers and angular's mock interval service for angular to recognize time changes . Here, the countDownService under test makes use internally of both javscript Date
and angular's normal interval service Something like:
describe('when start time was 3000 milliseconds and 1001 milliseconds have passed', function() {
var startTime;
var elapse;
beforeEach(function(){
this.clock = sinon.useFakeTimers();
startTime = 3000;
elapse = 1001;
});
var elapseMillis = function(intervalMock,sinonClock,millis){
sinonClock.tick(millis);
intervalMock.flush(millis);
};
it('elapsedMillis + timeRemainingMillis should == startime',
inject(function($rootScope,$interval,countdownService) {
countdownService.startTimer(startTime);
elapseMillis($interval,this.clock,elapse);
//jasmine clock does not mock Date
//see https://github.com/pivotal/jasmine/issues/361
var elapsedMillis = countdownService.getElapsedMillis();
var timeRemainingMillis = countdownService.getTimeRemainingMillis();
expect(elapsedMillis + timeRemainingMillis).toEqual(startTime);
expect(elapsedMillis).toEqual(elapse);
}));
afterEach(function(){
this.clock.restore();
startTime = 0;
elapse = 0;
});
});
You'll want to make sure and include sinon js's sinon-timers-1.8.1.js
in your karma.conf.js files property, too.