unit-testing - 在 angular js 中测试 Controller 时得到 Unknown provider

标签 unit-testing angularjs karma-runner

我有以下 Controller :

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

哪个依赖于以下服务 :
angular.module('samples.services', []).
    factory('Samples', function($http){
    // Service code
}

尝试过 测试 Controller 使用以下代码:
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() {

    });
});

但得到以下错误:
Error: Unknown provider: MainCtrlProvider <- MainCtrl.

P.s 尝试了以下 post ,似乎没有帮助

最佳答案

测试 Controller 的正确方法是使用 $controller :

ctrl = $controller('MainCtrl', {$scope: scope, Samples: service});

详细示例:
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() {

  });
});

关于unit-testing - 在 angular js 中测试 Controller 时得到 Unknown provider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14123306/

相关文章:

javascript - 在 AngularJS 中为 ng-keyup 添加延迟

angular - Jasmine 中的 xdescribe 与 fdescribe

在 Angular 中对指令 Controller 进行单元测试,而不使 Controller 成为全局的

javascript - 使用 Teaspoon 和 Jasmine 测试 DOM Ready

c# - NUnit 测试错误?预期为 <MyType> 但为 <MyType>

python - 单元测试+模拟+UWSGI

angularjs - 使用 HTML Unit 和 prerender.io 的 Angular SEO

javascript - AngularJS 选择更改触发器

node.js - Webpack 突然无法编译,因为 "Module not found: Error: Can' tsolve"错误

spring - 用于 Spring Boot 应用程序的 JUnit @BeforeClass 非静态工作