在使用Jasmine测试时,如何在控制器中触发$ emit来测试监听器上的$?

kon*_*ave 7 unit-testing jasmine angularjs

我有一个控制器,想用Jasmine测试它.我想测试的控制器范围内有一个$ on监听器.如何触发$ emit事件以在侦听器上运行$?

myApp.controller('superCtrl', function ($scope) {
    $scope.hero = 'Rafael ninja turtle';

    $scope.$on('change_hero', function (event, new_hero) {
        $scope.hero = new_hero;
    });
});
Run Code Online (Sandbox Code Playgroud)

当'change_hero'事件发生时,test $ on listener正常工作:

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

});
Run Code Online (Sandbox Code Playgroud)

Flo*_*n F 8

看起来你需要在创建控制器之前调用spyOn.此外,你应该调用andCallThrough()否则不会调用真正的方法,你的测试将失败