Jasmine/AngularJS:在单元测试中注入服务依赖服务?

nat*_*ate 7 jasmine angularjs karma-runner

我有角度模块:

var app = angular.module("SearchUI",[]);
Run Code Online (Sandbox Code Playgroud)

在它,我有一个服务"configService",维护一堆配置参数:

app.provider("configService",function(){
  //stuff here
})
Run Code Online (Sandbox Code Playgroud)

我在configService fineL中运行了jasmine单元测试

describe('configService',function(){

var configService,$httpBackend;


    beforeEach(module('SearchUI'));
    beforeEach(inject(function(_configService_,$injector){
        configService = _configService_;    
        $httpBackend = $injector.get("$httpBackend");

    }));

    it('should have default values for configService', function(){
        expect(configService.getDefaultSearch()).toEqual(['abstract','title','keyword','keywordplus'
    ]);
    });

//other stuff
Run Code Online (Sandbox Code Playgroud)

所有测试都通过了.

但是,我不了解如何在另一项服务中维持该注入:

即在我的申请中:

app.service("SearchService",function($http,$log,configService,$q){
    //stuff
    search_params = configService.getDefaultSearch();

})
Run Code Online (Sandbox Code Playgroud)

我的规格:

describe('SearchService',function(){
    var searchService,configService;

    beforeEach(module('SearchUI'));
    beforeEach(inject(function(_configService_,_SearchService_){
        configService = _configService_;    
        searchService = _SearchService_;

    }));


    it('SearchService should return results', function(){
        var waiting = searchService.SimpleSearch("card","wos",0);


//other stuff
Run Code Online (Sandbox Code Playgroud)

规范失败,因为在simplesearch函数中需要这样:

search_params = configService.getDefaultSearch(); //get the default search parameters       
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何将所需的服务注入到另一个服务中?

Bro*_*cco 5

服务只是 JavaScript 类,您可以创建它们的实例,而无需使用 angular 的注入机制来促进您的依赖注入。相反,您可以简单地自己创建类的新实例,同时提供所需的参数。

目前,您正在通过内联函数创建服务:

app.service("SearchService",function($http,$log,configService,$q){...

而不是通过进行小的调整,将服务的声明与其注入到 angular 模块中分开。这样做将允许您从测试访问服务类。

function SearchService($http, configService){...

app.service("SearchService", SearchService);
Run Code Online (Sandbox Code Playgroud)

从你的测试套件中,你可以在你的 beforeEach 预处理器中准备你的注入:

describe('configService',function(){

    var configService, httpBackend;
    beforeEach(module('SearchUI'));
    beforeEach(inject(function($httpBackend){
        httpBackend = "$httpBackend";
        configService = jasmine.createSpyObj('configService', ['getDefaultSearch']);
    }));

    /* helper method that I create to only have one place where the service is created 
    If I add a new param/dependency then I only have to change the construction once */
    function createService(){
        return new SearchService(httpBackend, configService);
    }
});
Run Code Online (Sandbox Code Playgroud)

采用这种方法进行测试(手动控制依赖注入而不是依赖 angular 的实现)的主要原因是完全控制并真正隔离我试图测试的项目。