Angularjs jasmine无法识别角度事件侦听器$on

Angularjs jasmine无法识别角度事件侦听器$on,angularjs,jasmine,karma-runner,Angularjs,Jasmine,Karma Runner,我添加了事件广播和发射,现在jasmine加载元素失败了 控制器函数是接收事件的,我想测试它如下 function Tree(scope, $http, dataservice, Block, events) { var $scope = scope; init(); function init(){ // React to global events $scope.$on(events.reloadOnNewData, onNe

我添加了事件广播和发射,现在jasmine加载元素失败了

控制器函数是接收事件的,我想测试它如下

    function Tree(scope, $http, dataservice, Block, events) {

    var $scope = scope;
    init();
    function init(){
        // React to global events
        $scope.$on(events.reloadOnNewData, onNewData);
    }
在Jasmine中,我在单元测试中有以下代码:

beforeEach(inject(function (_$controller_, _ParameterList_) {
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
    controller = $controller('Tree', {$scope: $scope});
}));
在业力形态中,我使用流动的角度模型

'./bower_components/jquery/dist/jquery.js',
        './bower_components/angular/angular.js',
        './bower_components/angular-mocks/angular-mocks.js',
        './bower_components/angular-animate/angular-animate.js',
        './bower_components/angular-route/angular-route.js',
        './bower_components/angular-sanitize/angular-sanitize.js',
当我运行测试时,我得到

    TypeError: $scope.$on is not a function

您需要实例化rootScope并将其传递到控制器中,这样它就不会显示此错误

  var $scope;
    beforeEach(inject(function (_$controller_, _ParameterList_,$rootScope) {
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $scope =  $rootScope.$new();
        $controller = _$controller_;
        controller = $controller('Tree', {$scope: $scope});
    }));
用这种方式定义我

var scope;
beforeEach(inject(function (_$controller_, _ParameterList_,$rootScope) {

    $controller = _$controller_;
    scope = $rootScope.$new()
    controller = $controller('Tree', {$scope: scope});
}));

但是现在作用域被rootscope更改了,所以如果任何变量依赖于本地作用域,比如$scope.selectedItem={}@Sonne no,则会出现错误-
$rootscope。$new()
创建了一个新的作用域,该作用域原型继承自
$rootscope
,但是这是(几乎)相同的机制无论如何都会创建角度中的所有范围。