How to return an object instead of a response string using nock?

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.

+6
source share
1 answer

There is nothing wrong with setting up your knockout, but you did not tell request parse the response as JSON.

From the request document (attention to me):

json - sets the body, but in the JSON representation of the value and adds the header Content-type: application / json. In addition, it parses the response body as JSON.

The callback argument receives 3 arguments:

  • Error when applicable (usually from an http.ClientRequest object)
  • Http.IncomingMessage Object
  • The third is the response body (String or Buffer or JSON object, if the json option is provided )

So you need to set the json property to true on your section.request object:

 var request = require('request'); // ... section.request.json = true; request(section.request, function (err, response, body) { //.. }); 
+6
source

Source: https://habr.com/ru/post/980345/


All Articles