How to check events in angular?

I need to verify that events are correctly thrown or broadcast, and also trigger events manually.

What is the best way to do this?

+63
angularjs javascript-events unit-testing angularjs-directive jasmine
Mar 07 '13 at 13:25
source share
3 answers

If you just need some kind of testing when starting and catching events, here's how I do it. To ensure that a specific event is fired ( $emit -ed or $broadcast -ed), a spy is the way to go. You need a reference to the area that will call $emit or $broadcast , and then just do something like this:

 spyOn(scope, "$emit") //run code to test expect(scope.$emit).toHaveBeenCalledWith("MY_EVENT_ID", other, possible, args); 

If you don't need or don't need to worry about the arguments passed with $emit , you can put $on in $rootScope and set a flag to know that the event was fired, Something like this:

 var eventEmitted = false; $rootScope.$on("MY_EVENT_ID", function() { eventEmitted = true; }); //run code to test expect(eventEmitted).toBe(true); 

For testing the functionality that is executed when an event is detected ( $on ), this is a bit easier. Just get $rootScope from the inject function and send the desired event.

 $rootScope.$broadcast("EVENT_TO_TEST", other, possible, args); //expects for event here 

Now I believe that this event handling will occur in a directive or controller (or both). To configure directory tests, see https://github.com/vojtajina/ng-directive-testing . To configure controller tests, see https://github.com/angular/angular-phonecat/blob/master/test/unit/controllersSpec.js#L27

Hope this helps.

+118
Mar 07 '13 at 22:22
source share

Following are the steps to follow for the $ broadcast event in angular JS

When initializing the initialization of the root window and scope, as shown below:

 var rootScope; var scopeStub = beforeEach(function() { inject(function($rootScope, _$controller_) { rootScope = $rootScope; scopeStub = $rootScope.$new(); $controller = _$controller_; }); }); 

After the controller generated a flight event using rootScope, as shown below:

 rootScope.$broadcast('eventName', parameter1); 
0
Sep 26 '16 at 20:21
source share

We used this syntax for A1

 =========== Controller ======== var vm = this; $scope.$on('myEvent', function(event, data){ console.log('event number', data.id); }); ============ Test ============= it('should throw myEvent', function() { var data = {}; $scope.$broadcast('myEvent', {id:1}); $scope.$broadcast('myEvent', {id:2}); $scope.$broadcast('myEvent', {id:3}); }); ============ Output ============ Chrome LOG: '--------------------------------------------' Chrome LOG: 'event number', 1 Chrome LOG: 'event number', 2 Chrome LOG: 'event number', 3 
0
Nov 30 '17 at 11:10
source share



All Articles