gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:15:01 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com