AngularJS - 间隔不会被刷新

ale*_*333 3 javascript angularjs angular-mock

我有角度服务功能,我愿意测试:

doSomeTask: function (ids, callback) {
  $http.put('/get_job', {'ids': ids}).success(function (data) {
    var statusCheck = $interval(function() {
      $http.get('check_status?=' + data.job_id).success(function (data) {
        if(data.completed) {
          $interval.cancel(statusCheck);
          // and do something...
        }
      });
    }, 2000);
  });
Run Code Online (Sandbox Code Playgroud)

以下测试:

describe('MyService', function() {

  var myService;
  var $httpBackend;
  var $interval;

  beforeEach(module('myModule'));

  beforeEach(inject(function(_$httpBackend_, _$interval_, $rootScope, MyService) {
    $httpBackend = _$httpBackend_;
    $interval = _$interval_;
    myService  = MyService;
  }));

  describe('doSomeTask', function () {
    beforeEach(function () {
      $httpBackend.expectPUT("/get_job").respond({ job_id: '123' });
      $httpBackend.expectGET("/status_check").respond({ completed: true });
    });

    it('should do it well', inject(function ($interval) {    
      var ids = [1,2,3];
      myService.doSomeTask(ids);

      $httpBackend.flush();
      $interval.flush();
    }));
  });
});  
Run Code Online (Sandbox Code Playgroud)

似乎我的间隔永远不会被冲洗(第二个期望永远不会得到满足,并且我在间隔体内的断点从未被激发).它似乎也在使用模拟(在flush实现中放置了一些推荐).Angular和mocks的版本是一样的......

我究竟做错了什么?我怎样才能刷新我的间隔?

23t*_*tux 5

我认为你必须$httpBackend.flush()在刷新间隔后再打一秒钟.测试在代码的这个位置执行日志时是否获得控制台输出:

doSomeTask: function (ids, callback) {
  $http.put('/get_job', {'ids': ids}).success(function (data) {
    var statusCheck = $interval(function() {
      console.log("flushed");
      $http.get('check_status?=' + data.job_id).success(function (data) {
        if(data.completed) {
          $interval.cancel(statusCheck);
          // and do something...
        }
      });
    }, 2000);
  });
Run Code Online (Sandbox Code Playgroud)

当你flushed在控制台中获得一个,然后调用第二个$httpBackend.flush(),第二个http请求被触发.

it('should do it well', inject(function ($interval) {    
  var ids = [1,2,3];
  myService.doSomeTask(ids);

  $httpBackend.flush();
  $interval.flush();
  // after this call, you should get a 'flushed' in your console
  $httpBackend.flush();
  // after this call, the second http should fire
}));
Run Code Online (Sandbox Code Playgroud)

解:

要刷新间隔,请指定要刷新的毫秒数,如下所示: $interval.flush(2000)