2016-05-03 34 views
1

我試圖建立通過茉莉HTTP GET請求的期望,但我得到以下錯誤:

TypeError: Cannot read property 'user' of undefined 

服務功能我想測試檢查像:

function getData() { 
    return $http.get('http://example.com/data') 
     .then(function (response) { 
      return response.data.example.user; 
     }); 
} 

以下數據A GET請求到URL 「http://example.com/data」 返回:

{ 
    "id": "1", 
    "example": { 
    "user": [ 
     { 
      "name": "John", 
      "wife": [ 
      { 
       "name": "Jane", 
       "age": "27" 
      } 
      ] 
     } 
    } 
} 

相應測試看起來是這樣的:

describe("Service: myService", function() { 
    beforeEach(module("myApp")); 

    var myService, $httpBackend; 

    beforeEach(inject(function (_myService_, _$httpBackend_) { 
     myService = _myService_; 
     $httpBackend = _$httpBackend_; 

     $httpBackend.whenGET("http://example.com/data").respond("some data"); 
    })); 

    afterEach(function() { 
     $httpBackend.verifyNoOutstandingExpectation(); 
     $httpBackend.verifyNoOutstandingRequest(); 
    }); 

    it("should call the correct URL", function() { 
     $httpBackend.expectGET("http://example.com/data"); 
     myService.getData(); 
     $httpBackend.flush(); 
    }); 

不知怎的,我不能夠儘快測試HTTP GET請求的服務功能(我想測試)返回一個嵌套的JSON屬性而不是整個JSON。

在此先感謝!

+0

你需要有效的JSON –

回答

2

API響應的數據應該是正確格式的模擬數據,這裏getData是方法期望的對象格式,以便可以從中返回用戶。像​​

代碼

$httpBackend.whenGET("http://example.com/data").respond({ 
    "id": "1", 
    "example": { 
    "user": [] //to keep you code working 
    } 
}) 
+0

謝謝。但是,如果模擬數據非常長,並且test.js包含多個包含不同模擬數據的http請求測試(假設所有這些測試都是如此大規模的:http://www.sitepoint.com/youtube-json -例/)?我是否應該將模擬轉換爲單獨的JSON文件,以避免使用成千上萬的模擬數據行溢出測試文件? –

+0

是的。你可以..或其他ypu可以維護在單獨的JavaScript文件中的數據.. –