我是否应该将功能从控制器移动到服务,但为了单元测试而必须使用 rootScope 而不是范围?
Should I move function from controller to a service, but then having to use rootScope instead of scope, for the sake of unit testing?
我有这个项目,我可以在其中使用控制器或服务中的功能。但是,如果只是为了单元测试而将函数放在服务中会更好,但我必须将我的变量绑定到全局范围。值得权衡吗?
如果将其移至服务中有意义,那么您绝对应该这么做。至于将它绑定到 $rootScope 作为 $scope 的替代方案,因为你正在移动它,也许你应该考虑 returning 控制器可以绑定到的服务函数的结果。例如:
.factory('YourService', function() {
return {
//needs to be theFunction: function theFunction, not theFunction:theFunction
theFunction: function theFunction(param1, ...) {
var results = ... some complicated logic ...
return results;
}
};
});
.controller('YourController', ['$scope', 'YourService', function($scope, YourService) {
...
$scope.results = YourService.theFunction($scope.param1, ...);
...
}]);
或者如果该函数执行一些异步功能,那么 return 一个承诺并在控制器中做这样的事情:
.controller('YourController', ['$scope', 'YourService', function($scope, YourService) {
...
YourService.theFunction($scope.param1, ...).then(function(results) {
$scope.results = results;
}, function(err) {...handle errors});
...
}]);
通过执行类似的操作远离 $rootScope 将使您的服务更易于测试,因为它具有更少的依赖性。
我有这个项目,我可以在其中使用控制器或服务中的功能。但是,如果只是为了单元测试而将函数放在服务中会更好,但我必须将我的变量绑定到全局范围。值得权衡吗?
如果将其移至服务中有意义,那么您绝对应该这么做。至于将它绑定到 $rootScope 作为 $scope 的替代方案,因为你正在移动它,也许你应该考虑 returning 控制器可以绑定到的服务函数的结果。例如:
.factory('YourService', function() {
return {
//needs to be theFunction: function theFunction, not theFunction:theFunction
theFunction: function theFunction(param1, ...) {
var results = ... some complicated logic ...
return results;
}
};
});
.controller('YourController', ['$scope', 'YourService', function($scope, YourService) {
...
$scope.results = YourService.theFunction($scope.param1, ...);
...
}]);
或者如果该函数执行一些异步功能,那么 return 一个承诺并在控制器中做这样的事情:
.controller('YourController', ['$scope', 'YourService', function($scope, YourService) {
...
YourService.theFunction($scope.param1, ...).then(function(results) {
$scope.results = results;
}, function(err) {...handle errors});
...
}]);
通过执行类似的操作远离 $rootScope 将使您的服务更易于测试,因为它具有更少的依赖性。