javascript - Unit testing an asynchronous service in angularjs -


i trying unit test service has asynchronous methods having no luck.

i have tried implement promises using $q support in angularjs.

any appreciated.

http://jsfiddle.net/9pbze/37/

angular.module('myapp', ['myservice']);  angular.module('myservice', []).factory('myservice', function($q) {   var ls = {};    ls.doit = function() {     var deferred = $q.defer();      settimeout(function(){         deferred.resolve(5);     },3000);      return deferred.promise;   }    return ls;  });  describe('services', function () {      beforeeach(module('myservice'));      it("should equal 2",  inject(function(myservice) {         myservice.doit().then(function(returned) {             expect(returned).toequal(2);         });             })); }); 

first of all, settimeout particularly tricky test since hard mock. fortunately angularjs has wrapper around ($timeout) plays same role can mocked:

  ls.doit = function() {     var deferred = $q.defer();      $timeout(function(){         deferred.resolve(5);     },3000);      return deferred.promise;   } 

the mock provided $timeout allows simulate elapsed time (with $timeout.flush()) means our tests can run fast, without waiting async event complete (please note production code still using async api!).

the changed tests like:

it("should equal 5",  inject(function(myservice, $timeout) {      var valuetoverify;     myservice.doit().then(function(returned) {       valuetoverify = returned;       });       $timeout.flush();             expect(valuetoverify).toequal(5); })); 

and working jsfiddle: http://jsfiddle.net/v9l9g/1/


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -