When I request a stub with nock , it returns a String result instead of Object even with 'Content-Type': 'application/json' :
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');
check:
console.log(put.response.body); console.log(put.response.body.id);
output:
{"status":"OK","id":"05056b27b82"} undefined
In the code, I use the request module, which returns an Object with the same data. I also tried sinon (not working for me) and fakeweb , but got the same problem.
My code I'm trying to check is:
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); });
And it returns an object in real queries.
PS . I could add the following code to the response handler:
if (_.isString(body)) body = JSON.parse(body);
But some requests return an xml string, and I am not responsible for such changes.
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);
The same results.
Updated:
I read several articles that use the JSON Object, without parsing it (with a toe), so it should return a JSON object, just like the request library does.