【问题标题】:Trouble getting jasmine working with angular让茉莉花与 Angular 一起工作时遇到问题
【发布时间】:2015-10-20 20:11:32
【问题描述】:

我无法理解如何设置 Jasmine 以与 Angular 一起使用,以便进行测试。我正在遵循标题为“测试控制器”标题下的说明here。根据文档,您应该像往常一样定义您的应用程序和控制器(这是从文档中粘贴的):

angular.module('app', [])
.controller('PasswordController', function PasswordController($scope) {
  //controller code goes here (removed for brevity)
});

然后你应该有你的测试套件代码,例如(从文档中粘贴)。

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

  var $controller;

  beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $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');
    });
  });
});

但我对一些事情感到非常困惑。

  1. 文档解释说您需要使用angular-mocks 来加载控制器,但在他们的示例中,他们没有将ngMocks 声明为应用依赖项(请参阅我上面粘贴的第一段代码)。
  2. 它说您可以使用angular.mock.inject 将控制器注入到当前上下文中。我在脚本http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-mocks.js 中加载,现在在全局范围内有一个angular.mock,但它没有inject 方法。此外,由于测试代码在控制器之外运行,我不明白在 Angular 应用程序中使用 ngMocks 依赖项如何有助于提供注入控制器的全局方法。整件事对我来说毫无意义。
  3. module 也是如此。它说你可以将它用于beforeEach(module('app'));,它是由angular-mocks 提供的,但是angular.mock 没有module 方法。

如果有人能解释我做错了什么,我将不胜感激!

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

    所以我发现问题在于我的 angular-mocks 脚本标签是 before 我的 Jasmine 脚本标签,而它确实需要 after。在 Angular “文档”的典型精神中,没有任何地方提到这一点。在重新排列脚本标签后,moduleinject 都是全局可用的方法。

    所以要回答我的第一个问题,您不需要将ngMock 放入依赖项中。这回答了问题 2 和 3,因为 moduleinject 现在都在全球范围内可用。

    所以脚本需要按这个顺序放置。

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine-html.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/boot.js"></script>
    <!--angluar mocks script MUST go after the other declarations otherwise it won't add the inject and module methods to the scope -->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-mocks.js"></script>
    

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      相关资源
      最近更新 更多