rahul aggarwal rahul aggarwal - 27 days ago 12
AngularJS Question

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

I am getting error while writing Angular JS Jasmine Unit Test cases:-

Cannot read property '$broadcast' of undefined

My Code:-

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


My UnitTest Code

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


});


Please help with code.

Answer

First, you double inject $rootScope but the root cause of the problem is that the $rootScope is undefined in it block, $rootScope is defined ONLY on beforeEach closure, you need to define it on describe level so it's later available in it block

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