在角度js测试控制器时得到了未知的提供者

Gal*_*cha 12 unit-testing angularjs karma-runner

我有以下控制器:

angular.module('samples.controllers',[])
  .controller('MainCtrl', ['$scope', 'Samples', function($scope, Samples){
  //Controller code
}
Run Code Online (Sandbox Code Playgroud)

哪个依赖于以下服务:

angular.module('samples.services', []).
    factory('Samples', function($http){
    // Service code
}
Run Code Online (Sandbox Code Playgroud)

试图使用以下代码测试控制器:

describe('Main Controller', function() {
  var service, controller, $httpBackend;

  beforeEach(module('samples.controllers'));
  beforeEach(module('samples.services'));
  beforeEach(inject(function(MainCtrl, Samples, _$httpBackend_) {

  }));

    it('Should fight evil', function() {

    });
});
Run Code Online (Sandbox Code Playgroud)

但得到以下错误:

Error: Unknown provider: MainCtrlProvider <- MainCtrl.
Run Code Online (Sandbox Code Playgroud)

Ps尝试了以下帖子,似乎没有帮助

Gal*_*cha 27

测试控制器的正确方法是使用$ controller:

ctrl = $controller('MainCtrl', {$scope: scope, Samples: service});
Run Code Online (Sandbox Code Playgroud)

详细示例:

describe('Main Controller', function() {
  var ctrl, scope, service;

  beforeEach(module('samples'));

  beforeEach(inject(function($controller, $rootScope, Samples) {
    scope = $rootScope.$new();
    service = Samples;

    //Create the controller with the new scope
    ctrl = $controller('MainCtrl', {
      $scope: scope,
      Samples: service
    });
  }));

  it('Should call get samples on initialization', function() {

  });
});
Run Code Online (Sandbox Code Playgroud)

  • 您无法将控制器作为依赖项加载的原因是因为控制器保存在注册表中并且没有提供程序.这就是为什么你得到上面的错误..只有值/常量/工厂/服务可以作为依赖项加载. (7认同)