Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test events in angular?

I need to test that events get correctly emitted or broadcast, and trigger events manually.

What's the best way to do this?

like image 356
Kenneth Lynne Avatar asked Mar 07 '13 13:03

Kenneth Lynne


People also ask

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 .

Which testing is used in Angular?

The Angular CLI downloads and installs everything you need to test an Angular application with the Jasmine test framework. The ng test command builds the application in watch mode, and launches the Karma test runner. The last line of the log is the most important. It shows that Karma ran three tests that all passed.

How do you test Angular components?

To run your tests using the Angular CLI, you use the ng test command in your terminal. As a result, Karma will open up the default browser and run all the tests written with the aid of Jasmine and will display the outcome of those tests.


1 Answers

If you're just needing some testing on event firing and catching, this is how I do it. For ensuring that a certain event gets fired ($emit-ed or $broadcast-ed), a spy is the way to go. You need a reference to the scope that will be calling the $emit or $broadcast, and then just to 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 want to worry about the arguments that are passed with the $emit, you can put an $on on the $rootScope and set a flag to know the event was emitted. Something like this:

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

For testing functionality that runs when an event is caught ($on), it's a little easier. Just get a $rootScope from the inject function and then send the desired event.

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

Now, I imagine this event handling would be happening in a directive or a controller (or both) For setting up directive tests, see https://github.com/vojtajina/ng-directive-testing. For setting up controller tests, see https://github.com/angular/angular-phonecat/blob/master/test/unit/controllersSpec.js#L27

Hope this helps.

like image 108
dnc253 Avatar answered Sep 28 '22 05:09

dnc253