如何角测试服务,$ Q

如何角测试服务,$ Q

问题描述:

我有一个简单的服务:

.factory('list', function($q, $timeout) { 
    return { 
     get: function() { 
      var dfd = $q.defer(); 

      $timeout(function() { 
       dfd.resolve(['label1', 'label2']); 
      }, 10); 

      return dfd.promise; 
     } 
    }; 
}); 

,并希望对其进行测试。所以我创建了:

describe('list', function() { 

    var list, labels; 

    beforeEach(module('app')); 
    beforeEach(inject(function($q, _list_) { 
     list = _list_; 

     spyOn(list, 'get').and.callThrough(); 

     list.get().then(function(result) { 
      labels = result; 
     }); 
    })); 

    describe('getting list of labels', function() { 

     it('should return list of labels', function() { 
      expect(labels).not.toBe(undefined); 
      expect(Array.isArray(labels)).toBeTruthy(); 
     }); 

    }); 

}); 

但问题是,即使函数中的回调函数没有执行,即使服务中的get方法返回promise。难道我做错了什么?我读到了Jasmine的callFake方法,但说实话,我没有看到使用它的一个要点。你能解释一下使用它有什么好处吗?顺便说一句,我有茉莉花2.0和角度嘲笑最新的角度。

+0

'beforeEach'将函数作为参数。如果你希望它是异步的,那么函数应该接受一个回调函数。检查这个quetion http://stackoverflow.com/q/25598353/1197333 – Ivancho 2014-09-24 12:46:02

+0

我真的不明白它应该如何工作。我现在已经'beforeEach(function(done))',但我什么时候该调用它?在'然后'里面(那不起作用)或者在外面(都不)? – Przemek 2014-09-24 13:02:18

答案很简单,我忘了它。由于我使用$ timeout的事实,我应该在之后调用flush