如何在Jasmine测试中测试$scope.$on事件?

10

我正在进行控制器的单元测试,我想要测试一个事件处理程序。假设我的控制器如下:

myModule.controller('MasterController', ['$scope', function($scope){
    $scope.$on('$locationChangeSuccess', function() {
        $scope.success = true;
    });
}]);

我应该在我的Jasmine测试中广播它吗?我应该发出它吗?有没有被接受的标准?


你试过我的解决方案了吗? - glepretre
你是怎么测试这个的,@MailmanOdd? - chepukha
我刚刚添加/接受了我的解决方案,希望能有所帮助。 - Adam Modlin
2个回答

17

我想出的解决方案如下:

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

我有点困惑,但是我不是已经回答了吗? - glepretre
1
这很相似,但调用 $scope.$digest 是不必要的。事实上,在我的应用程序(与这个简化的问题不同)中,它实际上会导致问题。此外,我相信在看到你的帖子之前已经解决了这个问题,从未再次检查过这个问题 - 抱歉! - Adam Modlin

4

我认为没有“被广泛接受的标准”,但是根据$location源代码,该事件被广播,因此我会模拟这种行为并以此方式进行测试:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接