2013-03-24 10 views
14

Ünite testi yapmaya çalıştığım basit bir servisim var. Ne olursa olsun, searchService bilinmeyen bir sağlayıcı ya da hizmet null (ne yazık ki testimin başarısız olmasına neden olmaz!).Jasmine'i kullanarak basit bir AngularJS servisini test etme

Yanlış yaptığım şey hakkında bir fikriniz var mı?

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

ben searchService yükler yüzden önbelleğe değerleri kontrol edebileceği bir birim test oluşturmak çalışıyorum:

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

cevap

21

parametre olmadan bir hizmet için çalışması gerektiğini şu, belki bu olabilir başlangıç ​​noktası:

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

    }); 
}); 

(Ayrıca buradan göz atabilirsiniz: How do I test an AngularJS service with Jasmine?)

+1

O var doğru yöne gidiyorum. Teşekkürler! Angular.module ('app') bıraktım ve sadece modül ('app') yaptım. Ve sonra değişti invoke etmek (geç oldu, benim parmaklarımın bir aklı vardı sanırım) – nathasm

+5

Duymak güzeldi. Bir yan not olarak, aslında modül ('app') gerçek modülün alayları oluşturmanıza izin veren angular.mock.module ('app') için bir kısayoldur. – Flolagale