Mocking dates in AngularJS / Jasmine tests

后端 未结 4 1363
一个人的身影
一个人的身影 2021-02-05 01:19

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:

4条回答
  •  逝去的感伤
    2021-02-05 01:57

    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.

提交回复
热议问题