3

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

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);
  });

并对其进行以下测试:

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();
    }));
  });
});  

似乎我的间隔永远不会被刷新(第二个期望永远不会得到满足,我在间隔体内的断点从未被触发)。似乎我正在使用模拟(在刷新实现中提出了一些建议)。Angular 和 mocks 的版本是一样的……

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

4

1 回答 1

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);
  });

当您flushed在控制台中获得 a 时,再调用第二个,然后$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
}));

解决方案:

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

于 2014-09-09T07:52:26.467 回答