注入器已创建.无法注册模块

injector already created. can not register a module

本文关键字:注册 模块 创建 注入器      更新时间:2023-09-26

我是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');
  }
});