【问题标题】:Angular testing with Karma: after injecting controller, $controller() is undefined使用 Karma 进行角度测试:注入控制器后,$controller() 未定义
【发布时间】:2015-02-22 01:24:54
【问题描述】:

我正在尝试使用 Karma 和 Jasmine 为 Angular 设置测试。我已经成功安装和配置了 Karma,但是我在使用 angular-mocks 时遇到了问题。下面在 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 FAILED) 错误(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();
  });
});

【问题讨论】:

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


    【解决方案1】:

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

    你也不需要测试$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();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 2016-04-07
      • 1970-01-01
      • 2019-05-01
      • 2020-12-07
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 2014-09-28
      相关资源
      最近更新 更多