Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 418
stonerichnau Avatar asked Oct 18 '13 04:10

stonerichnau


People also ask

How do I run a test case in AngularJS?

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.

How does scope work in AngularJS?

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.

Is AngularJS code unit testable?

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.

How is testing done in Angular?

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 .


1 Answers

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();
like image 106
ivarni Avatar answered Oct 14 '22 05:10

ivarni