testing - How do I test Angularjs factory stubbing $http? -
i have factory called songs
fetches songs each second 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}; });
i test it, , tried shown bellow think inject service in wrong way. when try run test outputs error: no pending request flush !.it it's not making http calls.
describe('songs', function(){ var httpstub, localservice; beforeeach(module('pearljam')); beforeeach(inject(function(_$httpbackend_, songs){ httpstub = _$httpbackend_; localservice = songs; })); it('lists songs', function(){ var httpresponse = { data: [1]}; httpstub.whenget('api/songs.json').respond(httpresponse); var serviceresponse = localservice.all; httpstub.flush(); expect(serviceresponse).tobe([1]); }); });
the expectget creates new expectation, telling angular respond given object when request made /api/songs.json. it's registering should no request fired here.
because invoke poller function in service, http request fire when service loaded.
and have stub response before http request fired (i.e. before service loaded). load pearljam module -> register expectation expectget -> load songs service
here stripped down code important part re-injecting config , $timeout services should work http://plnkr.co/edit/lbkxjtjbejexizbynpvf?p=preview
Comments
Post a Comment