I am unit testing a controller and I want to test an event handler. Say my controller looks like:
myModule.controller('MasterController', ['$scope', function($scope){
    $scope.$on('$locationChangeSuccess', function() {
        $scope.success = true;
    });
}]);
Would I broadcast that in my Jasmine test? Would I emit it? Is there an accepted standard?
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);
        });
    });
});
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