AngularJS Unit Testing: Attaching Data from $q.resolve() to object -


i'm testing service uses service api calls, let's call data service. data service tested elsewhere, i've abstracted away simple implementation contains empty functions; i'm returning data via deferred object , jasmine's spyon syntax.

the trouble i'm finding approach when data returned, it's not available on calling object, if used $httpbackend. aware use $httpbackend, i'd know if i've missed (simple or otherwise) in approach.

example section of code i'm trying test:

storethedata = dataservice.getsomedata(); storethedata.$promise.then(function(data) {      /*this work*/     console.log(data);      /*but not, when testing using $q*/     _.foreach(storethedata, function(storeddata) {         /*do each object returned*/     }); }); 

as side note, don't think situation helped ...$promise.then on line, ideally wouldn't change code (i'm providing test coverage written while ago...)

example of test:

beforeeach(     ...     dataservice = {         getsomedata: function () { }     };     getsomedatadeferred = $q.defer();     spyon(dataservice, "getsomedata").and.returnvalue({$promise: getsomedatadeferred.promise});     ... );  it(...     getsomedatadeferred.resolve([{obj: "obj1"}, {obj: "obj2"}]);     $scope.$apply();     ... ); 

with test described above, console.log(data) testable data accessible being passed .then(). data not available storethedata, storethedata[0].obj undefined. on debug, can see data if go through promise attached storethedata via storethedata.$$state.value

like said, know use $httpbackend instead, there way $q without changing code under test?

i've not found way $q.resolve, have solution doesn't involve using data service or changing code under test. good, because main things wanted avoid testing data service side effect , changing code.

my solution create $resource object via $injector...

$resource = $inject.get("$resource"); 

...then return in basic implementation of data service. means use $httpbackend respond request end point isn't reliant on data service's definition staying consistent.

dataservice = {     getsomedata: function () {         /* new code starts here */         var resource = $resource(null, null, {             get: {                 method: "get",                 isarray: true,                 url: "/getsomedata"             }         });          return resource.get();        /* new code ends here */     } }; ... $httpbackend.when("get", "/getsomedata").respond(...; 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -