让 jasmine 与 angular 一起工作时遇到问题

Trouble getting jasmine working with angular

我无法理解如何设置 Jasmine 以与 Angular 一起工作,以便我可以进行测试。我正在按照 "Testing a controller" 标题下的说明 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 方法。

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

所以我发现问题是我的 angular-mocks 脚本标签在 之前 我的 Jasmine 脚本标签确实需要在 之后。本着 Angular "documentation" 的典型精神,这在任何地方都没有提到。重新排列脚本标签后,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>