我有一个简单的服务,我正在尝试单元测试.无论我尝试什么,searchService是一个未知的提供者,或者服务是空的(这足以使我的测试失败!!).
任何人都有洞察我可能做错了什么?
angular.module('app').service('searchService',function( $q,_ ) { // _ is lodash var cache = [ { id: "current",name: "Current",description: "Search current data" },{ id: "historical",name: "Historical",description: "Search historical data" } ]; this.getSearchOptions = function() { var deferred = $q.defer(); deferred.resolve( angular.copy( cache ) ); return( deferred.promise ); }; this.getSearchOptionsByID = function( id ) { var deferred = $q.defer(); var searchOption = _.findWithProperty( cache,"id",id ); if ( searchOption ) { deferred.resolve( angular.copy( searchOption ) ); } else { deferred.reject(); } return( deferred.promise ); }; } );
我正在尝试创建一个加载在searchService中的单元测试,以便我可以检查缓存的值:
describe("Unit: Testing Services",function() { describe("Search Service:",function() { var service = null; beforeEach(function() { angular.module('app').service('_'); }); // I've also tried the commented out code below //beforeEach(inject(function(searchService) { //this.service = searchService; //})); //it('should contain an searchService',invoke(function(service) { it('should contain an searchService',function(searchService) { expect(searchService).not.to.equal(null); }); it('should contain two search options',function(searchService) { expect(searchService.getSearchOptions()).to.equal(2); }); }); });
以下内容应该适用于没有参数的服务,也许这可以是一个起点:
describe("Unit: Testing Services",function() { describe("Search Service:",function() { beforeEach(function() { angular.module('app'); }); it('should contain a searchService',inject(function(searchService) { expect(searchService).not.to.equal(null); })); it('should contain two search options',inject(function(searchService) { expect(searchService.getSearchOptions()).to.equal(2); })); }); });