我有角度模块:
var app = angular.module("SearchUI",[]);
在它,我有一个服务“configService”,维护一堆配置参数:
app.provider("configService",function(){ //stuff here })
我在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
所有测试都通过.
但是,我不了解如何在另一项服务中维持该注入:
即在我的申请中:
app.service("SearchService",function($http,$log,configService,$q){ //stuff search_params = configService.getDefaultSearch(); })
我的规格:
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
规范失败,因为在simplesearch函数中需要这样:
search_params = configService.getDefaultSearch(); //get the default search parameters
我的问题是,如何将所需的服务注入到另一个服务中?
服务只是JavaScript类,您可以创建它们的实例,而无需使用angular的注入机制来促进依赖注入.相反,您可以在提供所需参数的同时自行创建类的新实例.
目前,您正在通过内联函数创建服务:
app.service(“SearchService”,$q){…
而不是通过进行小的调整,将服务的声明从注入角度模块中分离出来.这样做将允许您从测试访问服务类.
function SearchService($http,configService){... app.service("SearchService",SearchService);
从您的测试套件中,您可以在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); } });
采用这种方法进行测试的主要原因(手动控制依赖注入而不是依赖于角度的实现)是完全控制并真正隔离我试图测试的项目.