TypeError:$ controller不是函数 - 使用jasmine的angularjs

时间:2016-01-04 16:27:49

标签: angularjs jasmine

我正在尝试使用Jasmine为AngularJS app设置测试。它遵循docs,但有点简单。 fiddle具有以下代码:

angular.module('myapp', [])
  .controller('MyCtrl', ['$scope', function MyCtrl($scope) {
    $scope.greeting = "hello";
  }]);

describe('My controller', function() {
  var $controller;
  module('myapp');
  inject(function(_$controller_) {
    $controller = _$controller_;

  });

  it('greets', function() {
    var $scope = {};
    var controller = $controller('MyCtrl', {
      $scope: $scope
    });
    expect($scope.greeting).toEqual('hello');
  })

});

Jasmine报告错误:TypeError: $controller is not a function.

如何纠正代码以摆脱此错误并能够测试控制器?

1 个答案:

答案 0 :(得分:7)

您需要实例化app模块,并使用$controller块为每个测试注入beforeEach

describe('My controller', function() {
    var $controller;

    beforeEach(module('myapp'));

    beforeEach(inject(function(_$controller_) {
        $controller = _$controller_;
    }));

    it('greets', function() {
        var $scope = {};
        var controller = $controller('MyCtrl', {
            $scope: $scope
        });
        expect($scope.greeting).toEqual('hello');
    })

});

演示: https://jsfiddle.net/f5ebb55f/6/