Unit testing 如何使用$scope.$on对角度控制器进行单元测试?
我的Angular应用程序中有一个带有事件侦听器的控制器,定义如下Unit testing 如何使用$scope.$on对角度控制器进行单元测试?,unit-testing,angularjs,jasmine,karma-runner,Unit Testing,Angularjs,Jasmine,Karma Runner,我的Angular应用程序中有一个带有事件侦听器的控制器,定义如下 angular.module('test').controller('TestCtrl', function($rootScope, $scope, testService) { [...] $scope.$on("myEvent", function(args, value) { testService.doStuff(value); }); }); it('does st
angular.module('test').controller('TestCtrl', function($rootScope, $scope, testService) {
[...]
$scope.$on("myEvent", function(args, value) {
testService.doStuff(value);
});
});
it('does stuff', inject(function($rootScope, $controller, testService) {
var scope = $rootScope.$new;
$controller('TestCtrl', {
$scope : scope
});
[...]
}));
这在应用程序本身中非常有效。但是,当我尝试单元测试控制器的功能时(使用Jasmine和Karma),每个测试方法都会抛出以下错误:
TypeError: $scope.$on is not a function in [...]/testController.js
我在测试方法中创建控制器,如下所示
angular.module('test').controller('TestCtrl', function($rootScope, $scope, testService) {
[...]
$scope.$on("myEvent", function(args, value) {
testService.doStuff(value);
});
});
it('does stuff', inject(function($rootScope, $controller, testService) {
var scope = $rootScope.$new;
$controller('TestCtrl', {
$scope : scope
});
[...]
}));
我可以通过将控制器改为使用rootScope
来解决此问题:
$rootScope.$on(...)
但是,当然,这个应用程序不再像预期的那样工作了。我还可以通过在测试代码中引入$on
方法来消除错误:
var scope = $rootScope.$new;
scope.$on = function() {};
但是,像这样嘲弄听者违背了测试我真正代码的目的
为什么测试代码没有在范围的方法上找到?(但是仍然在根范围上找到它…)
我在这里肯定缺少一些基本的东西,但即使在大量搜索和阅读Angular源代码之后,我仍然无法找到它。$rootScope.$new
是一个函数。您需要调用它($rootScope.$new()
):
it('does stuff',inject(函数($rootScope,$controller,testService){
var scope=$rootScope.$new();
$controller('TestCtrl'{
$scope:scope
});
[...]
}));
示例:谢谢!那真是一个令人尴尬的错误。。。(啊!)我不知道为什么我会这样写,但这个错误已经感染了我所有的测试类。