在 Angular.js 单元测试中 $scope 上没有 $on 函数,但在测试中在 $rootScope 上

No $on function on $scope in Angular.js unit tests, but is on $rootScope in test

我正在尝试 运行 一个简单的单元测试,它只创建一个控制器(一个同事写的,所以其他人可以添加他们自己的单元测试),但是我所做的更改甚至停止了这个从通过。同事不知道为什么它不起作用。这是简单的测试。

测试

describe("My Controller", function () {
    var $q, $controller, $scope, $rootScope;
    var createCtrl;
    beforeEach(function () {
        module('myModule');
    });
    beforeEach(inject(function (_$q_, _$rootScope_, _$controller_, _$httpBackend_) {
        $controller = _$controller_;
        $scope = _$rootScope_.$new();
        $scope.$parent = {
            dummyFn: function() {}
        };
        createCtrl = function createCtrl() {
            return $controller('MyController', {
                '$q': _$q_,
                '$scope': $scope
            });
        };
    }));
}));
describe("Controller stability", function() {
    it("should initialise the controller without error", function() {
        var controller = createCtrl();
    });
});

如您所见,上面的测试除了在创建控制器时捕获错误外什么也没做。

这是控制器中代码的模型:

代码

(function() {
    "use strict";
     const {angular} = window;
     angular.module('myModule', [])
     .controller('MyController', MyController);
     MyController.$inject = ['$routeParams', '$scope'];
     function MyController($routeParams, $scope) {
         var vm = this;
         $scope.$on('event-name', function(event, eventData) {
             vm.eventData = eventData;
             updateData();
         })
     }
})();

我得到的错误取决于我 运行 业力,但似乎松散相关。

如果我 运行 它形成带有 gulp 任务的命令行,我得到:

TypeError: undefined is not an object (evaluating 'current.$$listenerCount[name]') in dist/app/vendor.js
$on@dist/app/vendor<line number>

堆栈跟踪通过 angular 并返回到测试。

如果我 运行 它在 Karma 的调试中 window:

Uncaught TypeError: Cannot read property 'event-name' of undefined
at Scope.$get.Scope.$on (hostname.com:9876/base/dist/vendor.js:<line number>)

然后通过堆栈跟踪再次下降。

查看 $on 的代码,我不明白为什么它会以这两种不同的方式失败。

更改控制器代码以使用 $rootScope.$on 似乎可以缓和测试,但我不明白为什么测试需要这样做,而不是主应用程序。

为什么 $on 在测试中不在 $scope 上,而在主应用程序中?

这个问题是因为 $on 关心 $parent

它将检查父级并尝试查看那里是否有另一个侦听器,但是由于未创建父级 'properly' 它找不到它并死掉了。

相反,将其实例化为:

$scope.$parent = angular.extend(_$rootScope_.$new(), {
        dummyFn: function() {}
});

这样它将具有 angularjs 期望它在调用 $on 时具有的所有属性。