[英]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')
的調用module('someApp')
必須在調用inject($someDependency)
之前發生。
您正在使用注入功能錯誤。 正如文檔所述, 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');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.