how can superagent and nock work together?
Asked Answered
F

1

16

In node.js, I have trouble making superagent and nock work together. If I use request instead of superagent, it works perfectly.

Here is a simple example where superagent fails to report the mocked data:

var agent = require('superagent');
var nock = require('nock');

nock('http://thefabric.com')
  .get('/testapi.html')
  .reply(200, {yes: 'it works !'});

agent
  .get('http://thefabric.com/testapi.html')
  .end(function(res){
    console.log(res.text);
  });

the res object has no 'text' property. Something went wrong.

Now if I do the same thing using request:

var request = require('request');
var nock = require('nock');

nock('http://thefabric.com')
  .get('/testapi.html')
  .reply(200, {yes: 'it works !'});

request('http://thefabric.com/testapi.html', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body)
  }
})

The mocked content is displayed correctly.

We used superagent in the tests so I'd rather stick with it. Does anyone know how to make it work ?

Thank's a lot, Xavier

Fiedling answered 4/2, 2013 at 14:50 Comment(0)
E
13

My presumption is that Nock is responding with application/json as the mime type since you're responding with {yes: 'it works'}. Look at res.body in Superagent. If this doesn't work, let me know and I'll take a closer look.

Edit:

Try this:

var agent = require('superagent');
var nock = require('nock');

nock('http://localhost')
.get('/testapi.html')
.reply(200, {yes: 'it works !'}, {'Content-Type': 'application/json'}); //<-- notice the mime type?

agent
.get('http://localhost/testapi.html')
.end(function(res){
  console.log(res.text) //can use res.body if you wish
});

or...

var agent = require('superagent');
var nock = require('nock');

nock('http://localhost')
.get('/testapi.html')
.reply(200, {yes: 'it works !'});

agent
.get('http://localhost/testapi.html')
.buffer() //<--- notice the buffering call?
.end(function(res){
  console.log(res.text)
});

Either one works now. Here's what I believe is going on. nock is not setting a mime type, and the default is assumed. I assume the default is application/octet-stream. If that's the case, superagent then does not buffer the response to conserve memory. You must force it to buffer it. That's why if you specify a mime type, which your HTTP service should anyways, superagent knows what to do with application/json and why if you can use either res.text or res.body (parsed JSON).

Exophthalmos answered 4/2, 2013 at 15:59 Comment(2)
Thank's for your answer! res.body is empty, the whole res object contains the default structure but the mocked content is not in there. I guess it's not a mime type problem.Fiedling
OK, I'll try this out on my end and see what I come up with.Exophthalmos

© 2022 - 2024 — McMap. All rights reserved.