使用 Karma 进行角度测试:注入控制器后,$controller() 未定义

Angular testing with Karma: after injecting controller, $controller() is undefined

本文关键字:controller 未定义 控制器 注入 Karma 测试 使用      更新时间:2023-09-26

我正在尝试用Karma和Jasmine为Angular设置测试。我已经成功安装和配置了 Karma,但我在使用角度模拟时遇到了问题。在下面的 aTest.spec 中.js我包含一个简单的应用程序、控制器和测试规范来说明这个问题。谁能告诉我我做错了什么?

我的控制台从 Karma 输出:

Chrome 39.0.2171 (Mac OS X 10.8.5) ControllerForTest encountered a declaration exception FAILED
TypeError: undefined is not a function
    at Suite.<anonymous> (/Users/duncanmalashock/python_projects/scout/public/tests/unit/aTest.spec.js:19:20)
    at jasmineInterface.describe (/Users/duncanmalashock/python_projects/scout/node_modules/karma-jasmine/lib/boot.js:59:18)
    at /Users/duncanmalashock/python_projects/scout/public/tests/unit/aTest.spec.js:13:1

Chrome 39.0.2171(Mac OS X 10.8.5):执行 1 个错误(共 1 个)错误(0.004 秒/0.002 秒)

业力.js:

...
files: [
  'http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js',
  'angular/vendor/angular-mocks.js',
  'tests/unit/*.spec.js'
],
...

控制器:

var testApp = angular.module('testApp', []);
testApp.controller('ControllerForTest', ['$scope',
  function($scope) {
    $scope.data = {
      a: 'foo',
      b: 'bar',
      c: 'baz'
    };
  }
]);

aTest.spec.js:

describe('ControllerForTest', function() {
  module('testApp');
  var $controller;
  inject(function(_$controller_) {
      $controller = _$controller_;
  });
  var controller = $controller('ControllerForTest');
  it('is defined', function() {
    expect($controller).toBeDefined();
  });
});

模块实例化和服务注入应该发生在beforeEach中,而不是直接发生在describe块中。这将使它们可用于以下每个it

你也不需要测试$controller,这是一个 Angular 服务。请改为测试控制器。

describe('ControllerForTest', function() {
  var $controller;
  var ControllerForTest;
  beforeEach(function() {
    module('testApp');
    inject(function(_$controller_) {
        $controller = _$controller_;
    });
  });
  it('is defined', function() {
    // This line can also be in the beforeEach.
    // Saves having to repetitively instantiate the controller.
    ControllerForTest = $controller('ControllerForTest');
    expect(ControllerForTest).toBeDefined();
  });
});