Angular jasmine 无法识别事件侦听器 $on

Angular event listener $on is not recognised by jasmine

我添加了事件广播和发射,现在 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});
}));

并且在 karma conf 中我使用了流动的 angular mpdules

'./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});
    }));

这样定义 i 。

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

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