2013-03-24 53 views
14

我有一个简单的服务,我试图进行单元测试。无论我尝试什么,searchService都是一个未知的提供者,或者服务是空的(奇怪的是,这不会导致我的测试失败!!)。使用Jasmine测试简单的AngularJS服务

任何人都知道我可能会做错什么?

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

回答

21

下应无参数的服务工作,也许这可能是一个起点:

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

    }); 
}); 

(您也可以看看这里:How do I test an AngularJS service with Jasmine?

+1

它得到了我正朝着正确的方向前进。谢谢!我放弃了angular.module('app'),只是做了模块('app')。然后改变注入(这是迟到了,猜测我的手指有自己的想法) – nathasm 2013-03-25 02:08:12

+5

很高兴听到。作为一个方面说明,实际上module('app')是angular.mock.module('app')的一个快捷方式,它允许你创建真实模块的模拟。 – Flolagale 2013-03-25 12:47:06

相关问题