2015-06-30 75 views
0
I have a following code: 

    angular 
     .module('testApp') 
     .factory('testDataService', function ($http) { 
      function testDataService(){ 
       var self = this; 
       self.test = function(){ 
        //do something 
       } 

       self.test1 = function(){ 
        // do something     
} 
      } 

      return new testDataService(); 

When I try to write a test case like 

    beforeEach(function(){ 
     new testDataService(); 
    }); 

It gives some error like: 

> TypeError: '[object Object]' is not a constructor (evaluating 'new testDataService()') 

在testDataService中有很多函數,比如「test」,「test1」等。我無法測試剩餘的函數,因爲外層函數的範圍無法訪問。我無法獲得實例,因爲「var self = this」 請幫忙。如何在茉莉花中測試以下功能?

+0

你究竟想要測試什麼?你是否試圖測試你的應用程序可以創建你的工廠?你想測試你的應用程序編譯嗎?等等。這個問題需要更具體。 – mikeswright49

+0

這裏沒有足夠的細節來幫助你。以下是測試角度服務的示例。 https://github.com/angular/angular-seed/blob/master/app/components/version/version_test.js – timsmiths

+0

請閱讀編輯。謝謝。 – Ashwini

回答

1

不需要新的操作員來創建對象。

請檢查這一項

describe("\n\Testing factory", function() { 
     var factTestDataService; 

     beforeEach(inject(function (testDataService) { 
      factTestDataService= testDataService; 
     })) 


     it("factTestDataService test to defined",function(){ 

      expect(factTestDataService.test()).toBeDefined() 
     }) 
     it("factTestDataService test1 to defined",function(){ 

      expect(factTestDataService.test1()).toBeDefined() 
     }) 

     it("factTestDataService to defined",function(){ 

      expect(factTestDataService).toBeDefined() 
     })   
    }); 

你需要注入testDataService工廠並將其存儲在本地變量。

然後,您可以使用此工具訪問在該工廠中定義的方法,就像在角度中一樣,並且可以使用不同的Jasmine測試方法進行檢查。

+0

非常感謝:)它的作品! – Ashwini

0

您的工廠已經返回testDataService的新實例。沒有必要撥打new。當您嘗試在實例上調用new時,它會引發您看到的錯誤。

+0

請閱讀編輯。謝謝。 – Ashwini