superagent和nock如何一起工作?

xa4*_*xa4 16 javascript request node.js superagent nock

在node.js中,我很难让superagent和nock一起工作.如果我使用请求而不是superagent,它可以完美地运行.

以下是superagent无法报告模拟数据的简单示例:

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);
  });
Run Code Online (Sandbox Code Playgroud)

res对象没有'text'属性.有些不对劲.

现在,如果我使用请求做同样的事情:

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)
  }
})
Run Code Online (Sandbox Code Playgroud)

模拟的内容正确显示.

我们在测试中使用了superagent,所以我宁愿坚持下去.有谁知道如何使它工作?

谢谢你,Xavier

JP *_*son 13

我的推测是,Nock正在以application/json你的回应作为mime类型做出回应{yes: 'it works'}.看看res.bodySuperagent.如果这不起作用,请告诉我,我会仔细看看.

编辑:

试试这个:

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
});
Run Code Online (Sandbox Code Playgroud)

要么...

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)
});
Run Code Online (Sandbox Code Playgroud)

任何一个现在都有效.这是我相信的.nock没有设置mime类型,并且假定默认值.我假设默认是application/octet-stream.如果是这种情况,则superagent不会缓冲响应以节省内存.你必须强迫它缓冲它.这就是为什么如果你指定一个mime类型,你的HTTP服务应该是什么,superagent知道如何处理application/json以及为什么你可以使用res.text或者res.body(解析的JSON).