How can I test a $scope.$on event in a Jasmine test?

前端 未结 2 2330
再見小時候
再見小時候 2021-02-20 18:39

I am unit testing a controller and I want to test an event handler. Say my controller looks like:

myModule.controller(\'MasterController\', [\'$scope\', function         


        
2条回答
  •  孤城傲影
    2021-02-20 19:22

    The solution I came up with is as follows:

    describe('MasterController', function() {
        var $scope, $rootScope, controller, CreateTarget;
    
        beforeEach(function() {
            inject(function($injector) {
                $rootScope = $injector.get('$rootScope');
                $scope = $rootScope.$new();
    
                var $controller = $injector.get('$controller');
    
                CreateTarget = function() {
                    $controller('MasterController', {$scope: $scope});
                }
            });
        });
    
        describe('$locationChangeSuccess', function() {
            it('should set $scope.success to true', function() {
                controller = CreateTarget();
                $rootScope.$broadcast('$locationChangeSuccess');
                expect($scope.success).toBe(true);
            });
        });
    });
    

提交回复
热议问题