我試圖建立通過茉莉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。
在此先感謝!
你需要有效的JSON –