angularjs - Unit test controller with injected service -


i want test injected service being called in controller.

login.controller.js

angular.module('examplemodule')   .controller('loginctrl', ['$state', 'authservice',     function($state, authservice) {       var self = this;        self.submit = function() {         authservice.login(self.credentials)           .then(function(res) {             console.log('success');             $state.go('home');           }, function(res) {             if (res.status === 400) {               console.log('error')             }            });       };     }   ]); 

login.service.js

angular.module('examplemodule')   .factory('authservice', ['$http',     function($http) {       var authservice = {};        authservice.login = function(credentials) {         return $http.post('/api/authenticate', credentials);           .then(function(res) {             return res;           });       };        return authservice;     }   ]); 

login.controller.test.js

describe('controller: loginctrl', function() {   beforeeach(module('examplemodule'));    var ctrl, authservice;    beforeeach(inject(function($controller, authservice){     ctrl = $controller('loginctrl');     authservice = authservice;   }));     describe('submit function', function() {     beforeeach(function(){       ctrl.submit();     });      it('should call authservice', function() {       expect(authservice.login).tohavebeencalled();     });       });  }); 

how test whether authservice.login called? way i'm injecting authservice test, i'm getting these errors:

typeerror: 'undefined' not object (evaluating 'authservice.login(self.credentials).then') 

you need mock login() method , make return promise:

describe('controller: loginctrl', function() {   beforeeach(module('examplemodule'));    var ctrl, authservice, $q;    beforeeach(inject(function($controller, _$q_, authservice){     ctrl = $controller('loginctrl');     $q = _$q_;     authservice = authservice;   }));     describe('submit function', function() {     beforeeach(function(){       var deferred = $q.defer();       spyon(authservice, 'login').and.returnvalue(deferred.promise);       ctrl.submit();     });      it('should call authservice', function() {            expect(authservice.login).tohavebeencalled();     });       }); }); 

working plunker


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -