7

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

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

    $scope.$on('change_hero', function (event, new_hero) {
        $scope.hero = new_hero;
    });
});

当“change_hero”事件发生时,测试 $on 监听器工作正常:

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

});
4

1 回答 1

8

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

于 2013-11-08T13:29:57.060 回答