Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nock - how to mock binary response

I'm writing code interacting with PayPal classic API. The first part of this interaction is to send request to PayPal and get a token from them. For that I use simple https request:

function makePayPalRequestForToken(options, callback) {

var requestOptions = {
    host: config.paypal.endpoint,
    path: '/nvp?' + qs.stringify(options),
    method: 'GET'
};
var req = https.get(requestOptions, function(res) {
    var data = '';

    res.on('data', function(chunk) {
      data = data + chunk;
    });

    res.on('end', function() {
      callback(null, data);
    });
});

req.on('error', function(e) {
    callback(e);
});

}

It works perfectly ok with PayPal sandbox, however, now I want to unit test my code and I don't know how to mock the response I get from PayPal.

I checked that the row response from PayPal is following:

<Buffer 54 4f 4b 45 4e 3d 45 43 25 32 64 35 44 53 33 38 35 31 37 4e 4e 36 36 37 34 37 33 4e 26 54 49 4d 45 53 54 41 4d 50 3d 32 30 31 35 25 32 64 30 35 25 32 64 ...>

So it looks like binary data. I wanted to use nock to mock the response, but I wonder how I could do this? How to make nock to response with the binary version of my response?

I tried something like this:

nock('https://' + config.paypal.endpoint)
                    .filteringPath(function() {
                       return '/';
                     })
                    .get('/')
                    .reply(200, 'myresponse', {'content-type': 'binary'});

But then I'm getting:

Uncaught Error: stream.push() after EOF

and it looks like no data is send in the mocked response.

like image 368
Jakub Avatar asked May 23 '15 00:05

Jakub


1 Answers

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.

UPDATE: After some back and forth in the comments, it came to light that the specific issue OP is facing may be fixed by updating Node to v0.12.4 or later. This commit in particular looks like it might be relevant.

like image 140
Trott Avatar answered Oct 12 '22 01:10

Trott