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
Testing in AngularJS is achieved by using the karma framework, a framework which has been developed by Google itself. The karma framework is installed using the node package manager. The key modules which are required to be installed for basic testing are karma, karma-chrome-launcher ,karma-jasmine, and karma-cli.
AngularJS ScopeThe scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.
AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.
To run the test, you will only need to run the command ng test . This command will also open Chrome and run the test in watch mode, which means your test will get automatically compiled whenever you save your file. In your Angular project, you create a component with the command ng generate component doctor .
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With