我有以下 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/