[英]AngularJs Jasmine unable to call $scope method within $rootScope method
I have a method in my controller $scope.get
another method $rootScope.search
. 我的控制器
$scope.get
有一个方法。 $scope.get
另一个方法$rootScope.search
。 I am writing the unit tests using Karma and Jasmin. 我正在使用Karma和Jasmin编写单元测试。
When I am trying to test the method $rootScope.search
it throwing an error, what I am doing wrong? 当我尝试测试方法
$rootScope.search
时引发错误,我在做什么错?
Code is as follows: 代码如下:
Ctrl.js
App.controller('Ctrl', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.get = function(search){ // return some data from service };
$rootScope.search = function(data){
$scope.get(data);
};
}]);
Ctrl.spec.js
describe('Ctrl', function(){
beforeEach(module('app'));
var $controller, $scope = {}, $rootScope = {};
beforeEach(inject(function(_$controller_, _$rootScope_){
$controller = _$controller_;
$rootScope = _$rootScope_;
}));
describe('Data', function(){
beforeEach(function() {
$controller('Ctrl', { $scope:$scope, $rootScope:$rootScope});
spyOn($scope, 'get');
});
it('$rootScope.search', function(){
$rootScope.search();
expect($scope.get).toHaveBeenCalled();
});
})
});
Error 错误
TypeError: $scope.get is not a function at Scope.$rootScope.search
Please help. 请帮忙。
Actually I have to use the same from view as a global method.
实际上,从全局角度来看,我必须使用相同的方法。
If you want to provide global methods on $rootScope, do it from a .run
block instead of a controller. 如果要在$ rootScope上提供全局方法,请从
.run
块而不是控制器中执行。
App.run([$rootScope', function($rootScope){
function get = function(search){ // return some data from service };
$rootScope.search = get;
}]);
But putting common functions in a factory is the recommended approach. 但是建议将常用功能放在工厂中。
App.factory('mySearch', function(){
function get = function(search){ // return some data from service };
return { search: get };
});
Then inject the custom search in your controllers: 然后在您的控制器中注入自定义搜索:
App.controller('Ctrl', ['$scope', 'mySearch', function($scope, mySearch){
var vm = $scope;
vm.data = mySearch.search(data);
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.