如何在angularJs中单元测试全局函数,即$ rootScope.functionname

时间:2014-06-15 13:03:29

标签: angularjs unit-testing

我有一个基本的控制器,里面我有一个从不同的控制器调用的全局函数,它在正在运行的应用程序中运行得非常好。

现在有人知道如何对这个全局函数进行单元测试吗?

cntrl它包含函数

apmstore.controller('HeaderCtrl', function(authentication, $rootScope, $scope, loginService){

 // how to test this function called in the loginCtrl below
 $rootScope.setDropDownStatus = function(visID, user, userImg) {
        $scope.dropdown = visID;
        $scope.user = user; 
        $scope.imgUrl = userImg;
   };
 });

loginCtrl

apmstore.controller('loginCtrl', function($scope, authentication, loginService,
    $rootScope) {
authentication.isAuthenticated = false;

//Here is where its called, i want to unit test this    
$rootScope.setDropDownStatus(false, null, null);

$scope.templates = [ {url : '/login'}, {url : '/config'} ];
$scope.login = function() {
    loginService.login($scope);
}
});

我是否需要更改HeaderCtrl中的逻辑以便更容易测试,即分离到服务/工厂等?

任何人都知道如何解决这个问题?谢谢

2 个答案:

答案 0 :(得分:1)

试试这个:

it('should call setDropDownStatus ', inject(function($rootScope, $controller, authentication, loginService) {
    $scope = $rootScope.$new();

   //fake the setDropDownStatus function as we don't care where this function is created 
   //We only care about whether this function is called.
    $rootScope.setDropDownStatus = function(){

    }
    spyOn($rootScope, "setDropDownStatus");
    ////////

    ctrl = $controller('loginCtrl', {
      $scope: $scope,
      authentication: authentication,
      loginService: loginService,
      $rootScope: $rootScope
    });

    //verify that this function is called with expected parameters.
    expect($rootScope.setDropDownStatus).toHaveBeenCalledWith(false,null,null);

  }));

DEMO

答案 1 :(得分:0)

对你的上一个问题是肯定的。您不应该在一个控制器中定义一个函数并在另一个控制器中使用它。将其放入服务中并在需要的地方注入服务。