AngularJS : Need help to unit test a factory with promise -


i have factory uses promise resolve json file. should resolve file first time , return result when called again.

here factory

app.factory('getserverconfig', function ($q, $http, serverconfig) {    return function (filename) {     var deferred = $q.defer();      if (serverconfig.loaded) {       deferred.resolve("alreadyloaded");     } else {       $http.get(filename).then(function (result) {         serverconfig.setconfig(result.data);         deferred.resolve("loaded");       }, function (result) {         deferred.reject();       });     }     return deferred.promise;   }; }) 

and how test :

it('should hallo world', inject(function(getserverconfig) {     var promiseresult;      getserverconfig("server-config.json").then(function (result) {       promiseresult = result;     });      rootscope.$apply();     expect(promiseresult).tobe('loaded'); })); 

unfortunately, looks likes promiseresult never set. here plunker code : http://plnkr.co/edit/urpcjuudkqprav07g5nx?p=preview

the problem $httpbackend demands flush() (take @ flushing http requests), can mimic $http asynchronous behavior in test.

to solve it, store reference of $httpbackend (or inject again) , call $httpback.flush() after request has been made.

look:

it('should hallo world', inject(function(getserverconfig, $httpbackend) {   var promiseresult;    getserverconfig("server-config.json").then(function (result) {     promiseresult = result;   });    $httpbackend.flush();   expect(promiseresult).tobe('loaded'); })); 

if gonna use $httpbackend in of specs, consider storing in local variable, , set in beforeeach.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -