在AngularJS中测试$interval被触发3次

Testing that an $interval gets fired 3 times in AngularJS

本文关键字:3次 interval AngularJS 测试      更新时间:2023-09-26

我有一个AngularJS服务,看起来像这样(我已经删除了不相关的代码):

myApp.factory('myService', ['$interval', function ($interval) {
  return {
    startWatch: function(onSuccess) {
      var watcher = $interval(onSuccess, 250);
      return watcher;
    },
    stopWatch: function(watcher) {
      $interval.cancel(watcher);
    }
  };
}]);

要测试此服务,我有以下内容:

describe('myApp', function() {
    beforeEach(function() {
        module('myApp');
    });
    describe('myService', function () {
        var myService = null;
        beforeEach(inject(function (myService) {
            myService = myService;
        }));
        it('should run successfully 3 times', function() {
          var count = 0;
          var w = myService.startWatch(function() {
            count = count + 1;
            console.log('fired ' + count + ' times.');
          });
        });
    });
});

当测试运行时,它只运行一次。我不明白如何实际测试1。区间片段2。它被触发的次数。服务中会有随时间变化的信息。我想测试信息是否符合预期。出于这个原因,我试图在一段时间内测试一些东西。我该怎么做呢?

谢谢你的帮助!

Try $interval.flush(millis):

describe('myApp', function() {
    beforeEach(function() {
        module('myApp');
    });
    describe('myService', function () {
        var myService = null;
        var $interval = null;
        beforeEach(inject(function (myService) {
            myService = myService;
            $interval = _$interval_;
        }));
        it('should run successfully 3 times', function() {
          var count = 0;
          var w = myService.startWatch(function() {
            count = count + 1;
          });
          $interval.flush(751); // greater than 250 * 3
          expect(count).toEqual(3);
        });
    });
});

记住在你的测试中引用angular mock: http://code.angularjs.org/1.2.0/angular-mocks.js .该版本应该与你的angular版本相同。