2015-05-14 98 views
0

我想測試我的控制器中正在調用我的注入服務。注入服務的單元測試控制器

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(); 
    });  
    }); 

}); 

如何正確測試AuthService.login是否被調用?有了辦法,我注入AuthService到我的測試,我得到這些錯誤:

TypeError: 'undefined' is not an object (evaluating 'AuthService.login(self.credentials).then') 

回答

1

您需要模擬login()方法,並使其返回一個承諾:

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

相關問題