我有一个基本的控制器,里面我有一个从不同的控制器调用的全局函数,它在正在运行的应用程序中运行得非常好。
现在有人知道如何对这个全局函数进行单元测试吗?
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;
};
});
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
中的逻辑以便更容易测试,即分离到服务/工厂等?
任何人都知道如何解决这个问题?谢谢
答案 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);
}));
答案 1 :(得分:0)
对你的上一个问题是肯定的。您不应该在一个控制器中定义一个函数并在另一个控制器中使用它。将其放入服务中并在需要的地方注入服务。