我有这个工厂Songs
,它每秒从 API 中获取歌曲:
angular.module('pearlJam')
.factory('Songs', function($http, $timeout, Config){
var response = {list: []};
var onSuccess = function(result){
response.list = result.data.data;
$timeout(poller, Config.pollingTimeout);
};
var poller = function(){
$http.get('api/songs.json', Config.httpOptions).then(onSuccess);
};
poller();
return {all: response};
});
我想对其进行测试,我尝试过如下所示,但我认为我以错误的方式注入服务。当我尝试运行测试时,它输出Error: No pending request to flush !.这就像它没有进行http调用一样。
describe('Songs', function(){
var httpStub, localService;
beforeEach(module('pearlJam'));
beforeEach(inject(function(_$httpBackend_, Songs){
httpStub = _$httpBackend_;
localService = Songs;
}));
it('lists all songs', function(){
var httpResponse = { data: [1]};
httpStub.whenGET('api/songs.json').respond(httpResponse);
var serviceResponse = localService.all;
httpStub.flush();
expect(serviceResponse).toBe([1]);
});
});