2014-12-31 29 views
6

當我存根請求與nock它返回String結果代替Object即使'Content-Type': 'application/json'如何返回對象而不是字符串用於響應nock?

var response = { 
    success: true, 
    statusCode: 200, 
    body: { 
    "status": "OK", 
    "id": "05056b27b82", 
    } 
}; 

Test.BuildRequest(); 
Test.SendRequest(done); 

nock('https://someapi.com') 
    // also tried 
    // .defaultReplyHeaders({ 
    // 'Content-Type': 'application/json', 
    // 'Accept': 'application/json' 
    // }) 

    .post('/order') 
    .reply(200, response.body, 
    'Content-Type': 'application/json', 
    'Accept': 'application/json'); 

檢查:

console.log(put.response.body); 
console.log(put.response.body.id); 

輸出:

{"status":"OK","id":"05056b27b82"} 
undefined 

在代碼我使用request模塊返回Object與s ame數據。我也試過sinon(不適用於我)和fakeweb,但得到了同樣的問題。

我的代碼,我正在嘗試測試:

var request = require('request'); 
// ... 

request(section.request, function (err, response, body) { 
    if (err || _.isEmpty(response)) 
    return result(err, curSyndication); 

    //if (_.isString(body)) 
    // body = JSON.parse(body); 

    section.response.body = body; 
    console.log(body.id); // => undefined (if uncomment previous code - 05056b27b82) 

    _this.handleResponse(section, response, body, result); 
}); 

並返回實際請求的對象。

PS。我可以在我的響應處理程序中添加下一個代碼:

if (_.isString(body)) 
    body = JSON.parse(body); 

但是,某些查詢返回xml字符串,我不負責此類更改。

Fakeweb

fakeweb.registerUri({ 
    uri: 'https://someapi.com/order', 
    body: JSON.stringify({ 
    status: "OK", 
    id: "05056b27b82", 
    }), 
    statusCode: 200, 
    headers: { 
    'User-Agent': 'My requestor', 
    'Content-Type': 'application/json', 
    'Accept': 'application/json' 
    } 
}); 
Test.SendRequest(done); 

相同的結果。

更新時間:

我讀了幾篇文章,使用JSON對象,而不對它進行分析(與箭扣),所以它應該返回JSON對象,同樣的方式請求庫是如何做到這一點。

+0

nock返回JSON。要轉換爲Object,您需要使用JSON.parse將JSON轉換爲Object - > http://jsfiddle.net/5qaxtfz6/ –

+0

我更新了我的答案。 [請求](https://github.com/request/request)模塊返回一個對象 – zishe

+0

在[此問題](http://stackoverflow.com/questions/14689252/how-can-superagent-and-nock-work一起)它返回一個對象。 – zishe

回答

6

你的nock配置沒有問題,但是你還沒有告訴request將響應解析爲JSON。

request method文檔(強調我):

json - 設置的值體,但可以JSON表示,並增加了內容類型:應用/ JSON報頭。 此外,將響應正文解析爲JSON。

的回調參數得到3個參數:

  • 錯誤時適用(通常從http.ClientRequest對象)
  • 一個HTTP。IncomingMessage對象
  • 第三是響應體(字符串或緩衝區,或者JSON對象如果json選項提供

所以你需要設置json屬性truesection.request對象:

var request = require('request'); 
// ... 

section.request.json = true; 
request(section.request, function (err, response, body) { 
    //.. 
}); 
+0

感謝您的完整回答,我將在獎勵啓用後授予獎勵。 – zishe

相關問題