如何单元测试角控制器$范围。$吗? [英] How to unit test Angular controller with $scope.$on?
问题描述
我有一个事件侦听器的控制器在我的角度应用,定义如下:
I have a controller with an event listener in my Angular app, defined as follows.
angular.module('test').controller('TestCtrl', function($rootScope, $scope, testService) {
[...]
$scope.$on("myEvent", function(args, value) {
testService.doStuff(value);
});
});
这工作完全在应用程序本身。然而,当我试图单元测试控制器的功能(使用的茉莉花的和的噶的),每个测试方法引发以下错误:
This works perfectly in the app itself. However, when I try to unit test the functionality of the controller (using Jasmine and Karma), each test method throws the following error:
TypeError: $scope.$on is not a function in [...]/testController.js
我在测试方法创建控制器如下:
I create the controller in my test methods as follows.
it('does stuff', inject(function($rootScope, $controller, testService) {
var scope = $rootScope.$new;
$controller('TestCtrl', {
$scope : scope
});
[...]
}));
我可以改变我的控制器使用解决问题 rootScope
而不是:
$rootScope.$on(...)
但当然预期的应用程序不工作了。我还可以按在我的测试code引入 $关于
办法摆脱错误的:
var scope = $rootScope.$new;
scope.$on = function() {};
但嘲讽听众喜欢这种失败的测试目的,我真正的code的。
but mocking the listener like this kind of defeats the purpose of testing my real code.
为什么不试code找到 $关于
在 <$ C的方法$ C>范围 ?(但发现它 rootScope
,还是......)
Why doesn't the test code find the $on
method of the scope
? (But finds it on rootScope
, still...)
必须有一些基本的东西,我很想念这里,但我一直没能甚至很多google搜索和阅读角源$ C $ C的后看着办吧。
There must be something fundamental that I'm missing here but I haven't been able to figure it out even after lots of googling and reading the Angular source code.
推荐答案
$ rootScope。$新的
是一个函数。你需要调用它( $ rootScope $新的()
):
$rootScope.$new
is a function. You need to invoke it ($rootScope.$new()
):
it('does stuff', inject(function($rootScope, $controller, testService) {
var scope = $rootScope.$new();
$controller('TestCtrl', {
$scope : scope
});
[...]
}));
例普拉克:<一href=\"http://plnkr.co/edit/t1x62msmOQDkNItGzcp9?p=$p$pview\">http://plnkr.co/edit/t1x62msmOQDkNItGzcp9?p=$p$pview
这篇关于如何单元测试角控制器$范围。$吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!