注射器已经创build。 不能注册一个模块

我是Angular JS的新蜜蜂,并试图以适当的TDD方式制造出一些东西,但在testing中我得到这个错误:

注射器已经创build,不能注册一个模块!

这是我正在谈论的服务。

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; }]); 

这是对上述服务的testing

 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')的调用module('someApp')必须发生在你调用inject($someDependency)

您正在使用注入function错误。 正如文档所述, 注入函数已经实例化一个$注入器的新实例。 我的猜测是,通过将$ injector作为parameter passing给inject函数,您要求它实例化$ injector服务两次。

只需使用注入来传递您想要检查的服务。 在封面之下, 注入将使用实例化的$ injector服务来获取服务。

您可以通过将第二个beforeEach语句更改为以下来解决此问题:

 beforeEach(inject(function(_authorService_) { authorService = _authorService_; })); 

还有一件事要注意。 传递给注入函数的参数authorService已经用'_'封装,所以它的名字不会隐藏在describe函数中创build的variables。 这也logging在注射文件中 。

不知道这是什么原因,但是你之前应该是这样的:

 beforeEach(function() { inject(function($injector) { authorService = $injector.get('authorService'); } });