1

我在编写 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' }]);


});

请帮忙写代码。

4

2 回答 2

2

首先,您双重注入$rootScope ,但问题的根本原因$rootScope是在it块中未定义,$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');
    }));
});
于 2016-11-07T12:25:26.057 回答
-2

尝试更换

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

经过

spyOn(rootScope,'$broadcast').andCallThrough();
于 2016-11-07T12:20:12.957 回答