Angularjs 具有注入服务的单元测试控制器

Angularjs 具有注入服务的单元测试控制器,angularjs,unit-testing,jasmine,karma-jasmine,angular-services,Angularjs,Unit Testing,Jasmine,Karma Jasmine,Angular Services,对以下控制器进行单元测试的最佳方法是什么我在将AuthService正确注入控制器时遇到问题。我看到了很多不同的方法,但我不确定最佳做法是什么,即模拟与间谍? 我有这样一个简单的服务: angular.module('users') .factory('AuthService', ['$http', '$window', function($http, $window) { var authService = {}; a

对以下控制器进行单元测试的最佳方法是什么我在将
AuthService
正确注入控制器时遇到问题。
我看到了很多不同的方法,但我不确定最佳做法是什么,即模拟与间谍?

我有这样一个简单的服务:

   angular.module('users')
      .factory('AuthService', ['$http', '$window',
        function($http, $window) {
          var authService = {};

          authService.login = function(creds) {
            return $http.post('/auth', creds)
              .then(function(res) {
                $window.localStorage.exampleToken = res.data.returned_token;
                return res;
              });
          };

          authService.isLoggedIn = function() {
            if($window.localStorage.exampleToken) {
              return true;
            } else {
              return false;
            }
          };

          authService.clear = function() {
            delete $window.localStorage.exampleToken;
          };

          return authService;
        }]);
我的控制器:

   angular.module('users')
      .controller('ExampleCtrl', ['AuthService', 
        function(AuthService) {
          var vm = this;

          vm.isLoggedIn = AuthService.isLoggedIn();
        }]);
我未完成的测试:

 describe('ExampleCtrl', function() {
      beforeEach(module('users'));

      var ctrl;

      beforeEach(inject(function($controller) {
        ctrl = $controller('ExampleCtrl', {});
      }));

      describe('when logged in', function() {
        beforeEach(function() {
          // how do i mock the isLoggedIn function to 
          // return true
        });

        it('should return true', function() {
          expect(ctrl.isLoggedIn).toBe(true);
        });

      });

      describe('when not logged in', function() {
        beforeEach(function() {
          // how do i mock the isLoggedIn function to 
          // return false
        });

        it('should return false', function() {
          expect(ctrl.isLoggedIn).toBe(false);
        });

      });

    });

您只能使用以下功能的
callFake

通过将spy与and.callFake链接,所有对spy的调用都将委托给提供的函数


AuthService
注入测试的正确方法是什么?
var AuthService; //so that you can have a reference within all your test file
beforeEach(function() {
     inject(function(_AuthService_) {
       AuthService = _AuthService_;
     });
     spyOn(AuthService, 'isLoggedIn').and.callFake(function() {
          return true;
     });
});