注射器已经创建.无法注册模块

Pra*_*ain 44 javascript angularjs

我是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;
}]);
Run Code Online (Sandbox Code Playgroud)

这是对上述服务的测试

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

    });
})
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

zay*_*uan 62

如果您正在混合呼叫module('someApp'),inject($someDependency)您将收到此错误.

您的所有来电module('someApp')必须在您致电之前进行 inject($someDependency).


loy*_*own 7

您正在使用注入功能错误.正如文档所述,inject函数已经实例化了$ injector的新实例.我的猜测是,通过将$ injector作为参数传递给inject函数,您要求它实例化$ injector服务两次.

只需使用inject传入您要检查的服务即可.在封面下,inject将使用它实例化的$ injector服务来获取服务.

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

beforeEach(inject(function(_authorService_) {
    authorService = _authorService_;
}));
Run Code Online (Sandbox Code Playgroud)

还有一点需要注意.传递给inject函数的参数authorService 已用'_'包装,因此它的名称不会隐藏在describe函数中创建的变量.这也记录在注射文件中.