2015-10-13 159 views
0

這是我的服務角JS單元測試(噶茉莉花)

angular.module('providers',) 
    .provider('sample', function(){ 

     this.getName = function(){ 
      return 'name'; 
     }; 
     this.$get = function($http, $log, $q, $localStorage, $sessionStorage) { 
      this.getTest = function(){ 
       return 'test'; 
      }; 
     }; 
    }); 

這是我的單元測試

describe('ProvideTest', function() 
{ 
    beforeEach(module("providers")); 
    beforeEach(function(){ 
     module(function(sampleProvider){ 
     sampleProviderObj=sampleProvider; 
     }); 
    }); 
    beforeEach(inject()); 

    it('Should call Name', function() 
    { 
     expect(sampleProviderObj.getName()).toBe('name'); 
    }); 

    it('Should call test', function() 
    { 
     expect(sampleProviderObj.getTest()).toBe('test'); 

    }); 


}); 

我得到一個錯誤類型錯誤: '未定義' 是不是函數評估sampleProviderObj.getTest()

我需要一種方法來訪問此函數。$ get。請幫助

回答

1

您應該將您的服務注入測試。首先

beforeEach(inject(function(_sampleProvider_) { 
    sampleProvider = _sampleProvider_; 
    })); 
1

,你所需要的,因爲已經表示,注入的服務,您測試:替換此:

beforeEach(function(){ 
    module(function(sampleProvider){ 
    sampleProviderObj=sampleProvider; 
    }); 
}); 
beforeEach(inject()); 

與此有關。就像下面

beforeEach(angular.mock.inject(function ($injector) { 
    sampleProviderObj = $injector.get('sample'); 
})); 

其次,更重要的事情。示例沒有任何getTest函數。如果你真的需要測試這個功能,你應該把你的測試的一部分「執行」爲你的提供者的功能。然後測試getTest以前執行結果的功能。就像這樣:

it('Should call test', function() 
{ 
    var nestedObj = sampleProviderObj.$get(/*provide correct parameters for this function*/) 
    expect(nestedObj.getTest()).toBe('test'); 
}); 

但它不是一件好事,因爲(當sampleProviderObj.$get工作不正確的情況下),該測試可以正常失敗,即使nestedObj.getTest工作。

還有一件事,好像你需要,而這種注射服務$http$log$q$localStorage$sessionStorage給你提供者隨後將它們作爲參數。