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

时间:2014-08-16 13:01:16

标签: javascript angularjs

我有一个看起来像这样的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.它被解雇的次数。服务中的信息会随着时间的推移而变化。我想测试信息是否按预期运行。出于这个原因,我试图测试一些事情随着时间的推移。我该怎么做?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试$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);
        });
    });
});

请记住将角度模拟引用到您的测试中:http://code.angularjs.org/1.2.0/angular-mocks.js。版本应与您的角度版本相同。