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

前端 未结 2 2364
再見小時候
再見小時候 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:07

    I don't think there is "an accepted standard" but according to $location source code the event is broadcasted, so I would mock this behavior and test it this way:

    'use strict';
    
    describe('MasterController', function() {
      var MasterController,
          $rootScope,
          $scope;
    
      beforeEach(module('myModule'));
    
      beforeEach(inject(function($rootScope, $injector, $controller) {
        $rootScope = $rootScope;
        $scope = $rootScope.$new();
        MasterController = $controller('MasterController', {
          '$scope': $scope
        });
        $scope.$digest();
      }));
    
      describe('$locationChangeSuccess event listener', function() {
        it('should set $scope.success to true', function() {
          var newUrl = 'http://foourl.com';
          var oldUrl = 'http://barurl.com'
    
          $scope.$apply(function() {
            $rootScope.$broadcast('$locationChangeSuccess', newUrl, oldUrl);
          });
    
          expect($scope.success).toBe(true);
        });
      });
    });
    

提交回复
热议问题