I've got a controller and want to test it with a Jasmine. There is an $on listener in the scope of controller that I want to test. How do I trigger $emit event to run $on listener?
myApp.controller('superCtrl', function ($scope) {
$scope.hero = 'Rafael ninja turtle';
$scope.$on('change_hero', function (event, new_hero) {
$scope.hero = new_hero;
});
});
Test $on listener works proper when 'change_hero' event comes:
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');
});
});
Looks like you need to call spyOn before creating the controller. Also, you should call andCallThrough() otherwise the real method won't be called and your test will fail
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