单元测试 $scope.$on - 未捕获事件

Unit testing $scope.$on - event not caught

我有一个带有简单 $scope.$on 的控制器:

app.controller('MyController', function($scope) {
    $scope.$on("myBroadRcvr", function(event, data) {
        $scope.name = data.name;
        $scope.empID = data.empID;
    });
});

我试过这样的单元测试:

describe('MyController', function () {
    var $scope, super_controller;

    beforeEach(function(){
        module('myApp');

        inject(function($rootScope, $controller){
            $scope = $rootScope.$new();
            spyOn($scope, '$on');

            super_controller = $controller('MyController', {$scope: $scope});            
        });
    });

    it('should receive name as test', function (){

        var myData = {name: 'test', empID: 'eg7gg'},
        var sub_scope = $scope.$new();

        sub_scope.$broadcast('myBroadRcvr', myData);

        expect($scope.$on).toHaveBeenCalled();
        expect($scope.name).toBe('test');
    });
});

通过以上我得到:

Expected undefined to be 'test'.

您的 sub_scope$scope 的子级,但是 $broadcast 将事件 向下 范围层次结构发送,因此您的侦听器父范围(在本例中为 $scope)无法捕获它。您应该改用 $emit,例如:

sub_scope.$emit('myBroadRcvr', myData);

docs on $broadcast here

Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.

(对比$emit,向上发送。)


您的代码还有一个小语法错误:行 [​​=16=] 应该以 ; 结尾。