无法在 AngularJS Jasmine 单元测试中读取未定义的 属性 '$broadcast'

Cannot read property '$broadcast' of undefined in AngularJS Jasmine Unit Test

我在编写 Angular JS Jasmine 单元测试用例时遇到错误:-

无法读取未定义的 属性“$broadcast”

我的代码:-

    $scope.$on('getVersionData', function (event, data) {
    getVersion(data.RegistrationId, data.FacilityCode);
});

我的单元测试代码

    beforeEach(inject(function ($rootScope, $injector) {
    $scope = $rootScope.$new();
    $rootScope = $injector.get('$rootScope');
    spyOn($rootScope, '$broadcast').and.callThrough();
    $controller = $injector.get('$controller');

}));
it('Controller: getVersion: Checking if $scope variable set to expectedValues', function () {
    $rootScope('getVersionData', [{ RegistrationId: 7946531, FacilityCode: 'L' }]);
    expect($rootScope.$broadcast).toHaveBeenCalledWith('getVersionData', [{ RegistrationId: 7946531, FacilityCode: 'L' }]);


});

请帮忙写代码。

尝试替换

spyOn($rootScope, '$broadcast').and.callThrough();

来自

spyOn(rootScope,'$broadcast').andCallThrough();

首先,你双重注入 $rootScope 但问题的根本原因是 $rootScopeit 块中未定义,$rootScope 仅在 beforeEach 闭包上定义,您需要在 describe 级别定义它它稍后在 it

中可用
describe('whatever', function () {
    var $rootScope = null //define $rootScope on describe level

    beforeEach(inject(function (_$rootScope_, _$injector_) {
        $rootScope = _$rootScope_; //assign injected $rootScope to the variable from describe so it's available in tests
        $injector = _$injector_;
        $scope = $rootScope.$new();
        spyOn($rootScope, '$broadcast').and.callThrough();
        $controller = $injector.get('$controller');
    }));
});