Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
    });

});
like image 507
konclave Avatar asked Nov 08 '13 13:11

konclave


1 Answers

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

like image 196
Florian F Avatar answered Oct 02 '22 20:10

Florian F