【问题标题】:Unit testing controller with injected service具有注入服务的单元测试控制器
【发布时间】:2015-09-20 06:19:10
【问题描述】:

对以下控制器进行单元测试的最佳方法是什么? 我无法将AuthService 正确注入到我的控制器中。 我已经看到了很多不同的方法,但我不确定最佳做法是什么 - 即 模拟VS间谍?

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

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

      });

    });

【问题讨论】:

    标签: angularjs unit-testing jasmine karma-jasmine angular-services


    【解决方案1】:

    你只能使用JasminecallFake函数:

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

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

    【讨论】:

    • AuthService 实际注入我的测试的正确方法是什么?
    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多