带注入服务的单元测试控制器

时间:2015-05-14 23:31:32

标签: angularjs unit-testing jasmine karma-jasmine

我想测试我的注入服务是在我的控制器中调用的。

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 个答案:

答案 0 :(得分: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