Nock - how to mock with a binary response

I am writing code that interacts with the classic PayPal API. The first part of this interaction is to send a request to PayPal and receive a token from them. I use a simple https request for this:

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 great with PayPal sandboxing however now I want to unit test my code and I don't know how to mock the response I get from PayPal.

I have verified that the line response from PayPal is as follows:

<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 nok to poke fun at the answer, but I'm wondering how could I do that? How do I make a nok for an answer with a binary version of my answer?

I've tried something like this:

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

      

But then I get:

Unused error: stream.push () after EOF

and it looks like no data is being sent in the laughingstock response.

+3


source to share


1 answer


If you don't understand how to grab the response you are getting from the actual server and replicate it to a node then read the nock awesome write capability .

Use nock.recorder.rec()

to record the actual response from the server. Use nock.recorder.play()

to get results. It should be an object that you can bind to JSON. Put the JSON in a file and you can use it nock.load()

for use in your unit tests.



UPDATE: . After some comments and comments, it emerged that the specific issue the OP was facing could be fixed by updating Node to v0.12.4 or newer. This commitment , in particular, looks like it might be relevant.

+3


source







All Articles