How to run $ emit to test $ on a listener in a controller when testing it with Jasmine?

I have a controller and want to test it with Jasmine. In the controller class that I want to test, there is $ on listener. How to fire $ emit event to fire $ on listener?

myApp.controller('superCtrl', function ($scope) { $scope.hero = 'Rafael ninja turtle'; $scope.$on('change_hero', function (event, new_hero) { $scope.hero = new_hero; }); }); 

The $ test on the listener works correctly when the change_hero event arrives:

 describe('Super controller', function () { var $scope, super_controller; beforeEach(function(){ module('myApp'); inject(function($rootScope, $controller){ $scope = $rootScope.$new(); super_controller = $controller('superCtrl', {$scope: $scope}); spyOn($scope, '$on'); }); }); it('should change change hero on change_hero event', function (){ var new_hero = 'Ralf ninja turtle', sub_scope = $scope.$new(); sub_scope.$emit('change_hero', new_hero); expect($scope.$on).toHaveBeenCalled(); expect($scope.hero).toBe('Ralf ninja turtle'); }); }); 
+7
angularjs unit-testing jasmine
source share
1 answer

It looks like you need to call spyOn before creating the controller. In addition, you must call andCallThrough (), otherwise the real method will not be called and your test will fail.

+8
source share

All Articles