samedi 4 juillet 2015

How to write a test unit for a service that returns a promise

Here is my factory in my app.js

  app.factory('userInfoFacrory', ['$http' , "$q", function($http,$q){
    return {
           getNames:function(){
            var differed  = $q.defer();
            $http.get("http://localhost/ang/api/v1/users/names")
            .success(function(data) {
                differed.resolve(data);
            }).error(function(msg) {
                differed.reject(msg);
            });
            return differed.promise;
          }
    }
  }])

I use this factory in my controller like bellow , and it works fine :

 app.controller('mainController', ['$scope','userInfoFacrory','$log', function($scope,userInfoFacrory,$log){

    var promise = userInfoFacrory.getNames();
    promise.then(function (data) {
        $log.info(data); // I get my data correctly here
    }, function (msg) {
        $log.error(data);
    })
}])

And here , I've tried to write a test unit , with karma-jasmine

describe('userInfoFacrory', function() {
var  factory ,$rootScope,$scope,$q,onTaskComplete , promise;

       beforeEach(function() {
        module("testApp");
        inject(function ($injector) {   
            $q = $injector.get("$q");
            factory = $injector.get("userInfoFacrory");
            $rootScope = $injector.get("$rootScope");
            $scope = $rootScope.$new();
            promise = factory.getNames(); // this function comes from my factory which returns a promise 
        });      
      });

      it('should return a promise', function() {
          // This test will pass , so no error so far 
         expect(typeof promise.then).toEqual('function');
      });
});

But I can't figure out how to test to so if my promise will have my data ( that comes from my api ) or not , any suggestion would be appreciated.

thanks

Aucun commentaire:

Enregistrer un commentaire