stonerichnau stonerichnau - 3 months ago 14
AngularJS Question

How do I test $scope.$on in AngularJS

How do I test that the scope is populated after the broadcast? I've searched and found a few QA's here in stackexchange, but none answered my problem. The code is working alright, just don't know how to test it. May I add that I'm a novice to testing, and especially with Jasmine.

So, here's the code:

Service CrappySvc:

update: function() {
$rootScope.$broadcast('updatecrappy', Crappy.query());
}


Controller GetCrappyCtrl:

$scope.$on('updatecrappy', function(event, crap) {
$scope.crap = crap;
});


Jasmine:

beforeEach(inject(function($rootScope, $httpBackend, $controller, Crappy) {
rootScope = $rootScope;
scope = $rootScope.$new();
Crappy = mockCrappy;

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

ctrl = $controller('GetCrappyCtrl', {
$scope : scope,
Crappy : mockCrappy
});


}));

it('$scope.$on should have been triggered', function() {
rootScope.$broadcast('updatecrappy', [{id : 2, name : 'crappy'}]);
expect(rootScope.$broadcast).toHaveBeenCalledWith('updscenes', [{id : 2, name : 'crappy'}]);


});

Stone

Answer

You need to tell Jasmine to let the spy call the actual $broadcast function

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

If you don't use andCallThrough() the spy does nothing.

Jasmine Docs

EDIT

With Jasmine 2, the syntax would be

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