【问题标题】:How can I test a $scope.$on event in a Jasmine test?如何在 Jasmine 测试中测试 $scope.$on 事件?
【发布时间】:2014-06-19 19:33:53
【问题描述】:

我正在对一个控制器进行单元测试,并且我想测试一个事件处理程序。假设我的控制器看起来像:

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

我会在 Jasmine 测试中播放它吗?我会发射吗?有公认的标准吗?

【问题讨论】:

  • 你试过我的解决方案了吗?
  • 你是怎么测试这个的,@MailmanOdd?
  • 我刚刚添加/接受了我的解决方案,希望对您有所帮助。

标签: angularjs unit-testing jasmine


【解决方案1】:

我想出的解决方案如下:

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

【讨论】:

  • 我很困惑,但是,这不是我回答的吗?
  • 类似,但调用 $scope.$digest 是不必要的。事实上,在我的应用程序中(不同于这个简化的问题),它实际上导致了问题。另外,我相信我在看到您的帖子之前就解决了问题,并且再也没有检查过这个问题 - 抱歉!
【解决方案2】:

我认为没有“公认的标准”,但根据$location source code 广播事件,所以我会模拟这种行为并以这种方式进行测试:

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

【讨论】:

  • 谢谢。拯救了我的一天。
猜你喜欢
  • 2016-09-14
  • 1970-01-01
  • 2013-10-26
  • 1970-01-01
  • 2014-09-30
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
相关资源
最近更新 更多