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

时间:2014-12-23 21:24:44

标签: javascript angularjs unit-testing jasmine karma-runner

我试图用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 of 1(1失败)错误(0.004秒/0.002秒)

karma.conf.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();
  });
});

1 个答案:

答案 0 :(得分:0)

模块实例化和服务注入应该在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();
  });
});