注入器已创建.无法注册模块
injector already created. can not register a module
我是Angular JS的新手,并试图以适当的TDD方式从中做出一些东西,但在测试时我得到了这个错误:
注入器已经创建,无法注册模块!
这就是我所说的服务。
bookCatalogApp.service('authorService', ["$resource", "$q", function($resource, $q){
var Author =$resource('/book-catalog/author/all',{},{
getAll : { method: 'GET', isArray: true}
});
var authorService = {};
authorService.assignAuthors = function(data){
authorService.allAuthors = data;
};
authorService.getAll = function(){
if (authorService.allAuthors)
return {then: function(callback){callback(authorService.allAuthors)}}
var deferred = $q.defer();
Author.getAll(function(data){
deferred.resolve(data);
authorService.assignAuthors(data);
});
return deferred.promise;
};
return authorService;
}]);
这是对上述服务的测试
describe("Author Book Service",function(){
var authorService;
beforeEach(module("bookCatalogApp"));
beforeEach(inject(function($injector) {
authorService = $injector.get('authorService');
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
describe("#getAll", function() {
it('should get all the authors for the first time', function() {
var authors = [{id:1 , name:'Prayas'}, {id:2 , name:'Prateek'}];
httpBackend.when('GET', '/book-catalog/author/all').respond(200, authors);
var promise = authorService.getAll();
httpBackend.flush();
promise.then(function(data){
expect(data.length).toBe(2)
});
});
it('should get all the authors as they have already cached', function() {
authorService.allAuthors = [{id:1 , name:'Prayas'}, {id:2 , name:'Prateek'}];
var promise = authorService.getAll();
promise.then(function(data){
expect(data.length).toBe(2)
});
});
});
})
如果您混合呼叫module('someApp')
和inject($someDependency)
,您将得到此错误。
所有对module('someApp')
的调用必须发生在对inject($someDependency)
的调用之前
您错误地使用了inject函数。正如文档所述,inject函数已经实例化了一个新的$injector实例。我的猜测是,通过将$injector作为参数传递给inject函数,你要求它实例化$injector服务两次。
只需使用inject传入你想要检查的服务。在底层,inject将使用它实例化的$injector服务来抓取服务。
你可以通过修改第二个beforeEach语句来解决这个问题:beforeEach(inject(function(_authorService_) {
authorService = _authorService_;
}));
还有一件事要注意。传递给inject函数的参数authorService已经用'_'封装了,所以它的名字不会隐藏在describe函数中创建的变量。
不确定这是原因,但是你的beforeEach应该是这样的:
beforeEach(function() {
inject(function($injector) {
authorService = $injector.get('authorService');
}
});
相关文章:
- Javascript,访问一个主要对象模块模式中的每个对象
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- 如何从模块链中调用函数.导出到节点中
- 尽管链接成功并已成功下载,但未找到NPM模块
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- 从模块内部访问Express装载路径
- RequireJS向模块传递配置总是返回undefined
- Node.js正在更改应用程序以使用集群模块
- 在Meteor项目中安装并包含npm模块后出错
- 模块模式和这个
- 将依赖外部库的UMD模块与browserfy捆绑在一起
- 点击facebook像素跟踪注册(JS/JQUERY代码)
- 未捕获错误:模块未自注册
- 错误:模块未自行注册
- 我可以得到所有注册模块的列表在我的Gruntfile.js
- 从typescript模块中注册Knockout.js组件视图模型
- 注入器已创建.无法注册模块
- 绑定错误.模块没有自我注册
- 如果我在两个模块中注册两个具有相同名称的不同指令,最后一个注册会获胜吗?
- 注册多个模块