How to return object instead of string for response with nock?

How to return object instead of string for response with nock?

By : Quickbooks Singapore
Date : November 22 2020, 10:54 AM
Any of those help There is nothing wrong with your nock configuration however you haven't told request to parse the response as JSON.
From the request method documentation (emphasis on me):
code :
var request = require('request');
// ...

section.request.json = true;
request(section.request, function (err, response, body) {

Share : facebook icon twitter icon
How to decode nock recorded response

How to decode nock recorded response

By : Amiy Amritansh
Date : March 29 2020, 07:55 AM
help you fix your problem The response from the http request is coming back as gzipped data, indicated by the content-encoding header. Nock is saving this data a hex encoded buffer string.
You can convert these cassettes into json with the following utility:
code :
var zlib = require('zlib');
var fs = require('fs');
var argv = process.argv.slice(2);
var path = require('path');

var filename = path.resolve(argv[0]);
var file = fs.readFileSync(filename, { encoding: 'utf8' });
var cassettes = JSON.parse(file);

cassettes.forEach(function (cassette) {
  if (cassette.headers['content-encoding'] !== 'gzip') {

  var response = new Buffer(cassette.response[0], 'hex');

  var contents = zlib.gunzipSync(response).toString('utf8');

  cassette.response = JSON.parse(contents);
  delete cassette.headers['content-encoding'];

fs.writeFileSync(filename, JSON.stringify(cassettes, null, 2), { encoding: 'utf8' });
Nock - how to mock binary response

Nock - how to mock binary response

By : user3685337
Date : March 29 2020, 07:55 AM
like below fixes the issue If you are at a loss as to how to capture the response you are getting from the actual server and replicate it in nock, then read up on nock's awesome recording capability.
Use nock.recorder.rec() to record the actual response from the server. Use nock.recorder.play() to get the results. It should be an object which you can stringify to JSON. Put the JSON in a file and you can use nock.load() to use in your unit tests.
why is it necessary to return a Response object instead of String object to an http request in java?

why is it necessary to return a Response object instead of String object to an http request in java?

By : user5719204
Date : March 29 2020, 07:55 AM
I wish this help you If you return a simple String, you don't have control over what happens in case of error. But if you return Response object you can return a proper 500 error with a fault message:
code :
try {
    return Response.ok(successResult).build();
} catch(Exception ex) {
    return Response.serverError().entity(fault).build();
    return Response.status(500).entity(fault).build();
Response response = Response.ok(successResult);

response.getHeaders().put("Access-Control-Allow-Origin", "*");
        "origin, content-type, accept, authorization");
response.getHeaders().put("Access-Control-Allow-Credentials", "true");
File fileToSend = getFile();
return Response.ok(fileToSend, "application/zip").build();
Mocking NodeJS request and response with Nock

Mocking NodeJS request and response with Nock

By : eoinmc
Date : March 29 2020, 07:55 AM
may help you . TLDR: I think your code is doing more than what it tells you.
Important note: when putting an http request in "stream mode" the data event could (and probably does) gets fired multiple times, each one for a "chunk" of data, over internet chunks could be variable between 1400 to 64000 bytes, so expect multiple callback invocations (that's a very special kind of bad)
code :
var assert = require('assert');
var https = require('https');
var nock = require('nock');

function externalService(callback) {
  // directly from node documentation:
  // https://nodejs.org/api/https.html#https_https_get_options_callback
  https.get('https://encrypted.google.com/', (res) => {

    var data = '';
    res.on('data', (d) => {
      data += d;

    res.on('end', () => callback(null, JSON.parse(data), res));
  // on request departure error (network is down?)
  // just invoke callback with first argument the error
  }).on('error', callback);

describe('Learning nock', () => {
  it('should intercept an https call', (done) => {
    var bogusMessage = 'this is not google, RLY!';

    var intercept = nock('https://encrypted.google.com').get('/')
      .reply(200, { message: bogusMessage });

    externalService((err, googleMessage, entireRes) => {
      if (err) return done(err);

      assert.strictEqual(googleMessage.message, bogusMessage);
      assert.strictEqual(entireRes.statusCode, 200);


How to get the response from nock

How to get the response from nock

By : Smeet Sanghani
Date : March 29 2020, 07:55 AM
hope this fix your issue Nock does not return {status:200} because it's intercepting POST request, but the request statement is sending GET request.
It seems you want to intercept POST request with specified profile? The code would be:
code :
var nock = require('nock');
var request = require('request');

const profile = {
  name: 'John',
  age: 25

const scope = nock('https://mydomainname.local')
  .post('/api/send-profile', profile)
  .reply(200, {status:200});

request.post('https://mydomainname.local/api/send-profile', {json: {name: 'John', age: 25}}).on('response', function(request) {
  console.log(request.statusCode); // 200
Related Posts Related Posts :
  • javascript - explanation request of a behaviour
  • Converting String into date format in JS
  • Choose element Angular
  • Display background grid by using image with CSS
  • Call function from another Controller in another file AngularJS
  • How to change texture in Gera library?
  • When trying to use windows.location.href , the values of $_POST[''] is lost
  • jQuery click action on appended item
  • NodeJS & Socket.IO: Emit a request event and get the response, when/where should I bind the listener?
  • 4-digit form on bootstrap modal
  • Prevent characters like quotation marks from input
  • Sign in option creation using jsp and oracle database
  • use socket.io in my controller with yeoman
  • What happens under the hood to prevent calling a bound method changing the this object?
  • issue with jquery .append function
  • Is it possible to EventHandle every GET request a page makes via Javascript?
  • How to select class with ng-if
  • Cannot communicate with websocket. Autobahn: received HELLO message, and session is not yet established
  • Socket.io - Cannot connect to client
  • Load Accordian Panel on click rather than page load
  • How to register async middleware module within express.js app?
  • JS / Cannot read property 'push' of undefined
  • how to make jquery plugin?
  • MATH reverting rotated coordinates
  • Add an expandable text box to every post
  • What was the rationale behind having the receiver in functions default to the global object?
  • JavaScript chaining many function
  • while loop over takes the each method
  • What are the difference between $(document).bind('ready', function) and $(document).ready(function() {})
  • cut the string in javascript
  • Tool tip not working on text area bootstrap
  • AngularJS: how to activate first non zero item in ngRepeat?
  • Pattern for "column total" of an array of arrays
  • Any selector using * failed in my case
  • Uncaught ReferenceError: app is not defined in Angularjs
  • Unit testing controller which has a $state.go method in controller
  • Use of Meteor-ui-progress-circle (accessing to Template variables created in the HTML)
  • JavaScript: Google maps mapOptions?
  • How do I track Universal Analytics events through Google Tag Manager?
  • Firefox Scrolling Bug When Changing :after Contents
  • Drop down list does not work
  • Display month and year specific datepicker in jquery
  • How to show BAr graph rather than line graph in High Stoch Chart
  • Accessing Angular $Scope in web workers
  • How to convert JavaScript(UnityScript) to C# and implement a low pass filter?
  • Need a logic to implement select button value via onchange event
  • redirect in codeigniter using ajax function
  • How to populate this form data and post it with jquery
  • Retrive value from array id in js function
  • angularjs $index when ng-hide with ng-repeat
  • ExtJS TaskRunner
  • Progress bar not hiding after fetching values via AJAX in JavaScript
  • Pop up window code fails
  • how to make dynamic javascript array with key and value group
  • Implement Facebook API login with reactjs
  • What is the meaning of sign ':' in javascript
  • Change all id's in HTMLDivElement using jQuery
  • load multiple pages from different domain in different divs using javascript
  • Could Not Resolve Host github.com
  • jQuery "Chosen" on-filter event?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org