我是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)
});
});
});
})
任何帮助将不胜感激。
答案 0 :(得分:62)
如果您要调用module('someApp')
和inject($someDependency)
,则会收到此错误。
在致电module('someApp')
之前,您必须拨打inject($someDependency)
的所有电话。
答案 1 :(得分:7)
您使用注入功能错误。作为documentation状态, inject 函数已经实例化了$ injector的新实例。我的猜测是,通过将$ injector作为参数传递给inject函数,您要求它实例化$ injector服务两次。
只需使用 inject 传递您要检查的服务即可。在封面下, inject 将使用它实例化的$ injector服务来获取服务。
您可以通过将第二个 beforeEach 语句更改为:
来解决此问题beforeEach(inject(function(_authorService_) {
authorService = _authorService_;
}));
还有一点需要注意。传递给 inject 函数的参数authorService已用'_'包装,因此它的名称不会隐藏在 describe 函数中创建的变量。那也注入了注入documentation。
答案 2 :(得分:1)
不确定这是原因,但您的beforeEach应该是这样的:
beforeEach(function() {
inject(function($injector) {
authorService = $injector.get('authorService');
}
});