【问题标题】:Testing non-scope functions in Angular Controller with Jasmine使用 Jasmine 在 Angular 控制器中测试非作用域函数
【发布时间】:2015-09-18 10:40:34
【问题描述】:

Jasmine 是以 BDD 方式对 javascript 代码进行单元测试的最广泛使用的测试框架之一。我尝试将它用于 AngularJS 组件测试。 AngularJS 文档提供了如下示例代码

describe('PasswordController', function() {
  beforeEach(module('app'));
  var $controller;

  beforeEach(inject(function(_$controller_){
    $controller = _$controller_;
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      var $scope = {};
      var controller = $controller('PasswordController', { $scope: $scope });
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
  });
});

所以上面的代码使用了 Angular 模拟库,并通过依赖注入通过控制器处理范围。现在我有一个范围对象,其中包含我的控制器分配给它的功能和对象。我可以很好地测试它。快乐。

现在有趣的部分是如果我想测试未链接到范围的函数。比如下面的doSomethingVeryCoolThatNeedsTesting函数

angular.module('app', [])
.controller('PasswordController', function PasswordController($scope) {
  $scope.password = '';
  $scope.grade = function() {
    var size = $scope.password.length;
    if (size > 8) {
      $scope.strength = 'strong';
    } else if (size > 3) {
      $scope.strength = 'medium';
    } else {
      $scope.strength = 'weak';
    }

   function doSomethingVeryCoolThatNeedsTesting() {
    ....  
   }

  };
});

似乎每当我使用$controller('PasswordController', { $scope: $scope }); 时,它都会返回一个填充的$scope 对象和undefined 控制器对象。

TL;DR

有没有一种方法可以测试未链接到范围的 Angular 控制器功能?

【问题讨论】:

    标签: javascript angularjs unit-testing jasmine


    【解决方案1】:

    没有。只要您不向外界公开内部控制器功能,这些功能是私有的,请参阅revealing module pattern

    所以问题既不是测试框架也不是角度问题,问题是javascript语言本身。

    如果你想测试一个内部函数,你必须让它对外部可见。选项有:

    1. 在 $scope 对象上公开它
    2. 强烈建议不要暴露在任何其他全局对象上,并且可能无法通过测试访问

    【讨论】:

      【解决方案2】:

      我会选择以下解决方案之一:

      1. 如果是私有函数,可能不应该直接测试,而是通过公共api测试
      2. 如果它是一个实用函数,那么它可能应该作为公共 api 在自己的控制器/服务中

      否则你必须污染你的控制器 api。我建议不要。迟早会有开发者开始使用这个半隐藏功能

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多