javascript - superagent 和 nock 如何协同工作?

标签 javascript node.js request superagent nock

在 node.js 中,我无法让 superagent 和 nock 一起工作。如果我使用请求而不是 super 代理,它会完美运行。

这是一个简单的例子,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);
  });

res 对象没有“文本”属性。出了点问题。

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

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)
  }
})

模拟的内容显示正确。

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

非常感谢, 泽维尔

最佳答案

我的假设是 Nock 使用 application/json 作为 mime 类型进行响应,因为您使用 {yes: 'it works'} 进行响应。查看 Superagent 中的 res.body。如果这不起作用,请告诉我,我会仔细查看。

编辑:

试试这个:

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
});

或者...

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)
});

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

关于javascript - superagent 和 nock 如何协同工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14689252/

相关文章:

node.js - 具有多个条件的聚合和基于计数键的总和匹配

Android - 加载 HTTP URL 而不显示页面的任何内容?

javascript - 在函数内对编号数组进行排序

javascript - 如何简化此 switch 语句(Angular 应用程序)

javascript - 单击时使用不同的文本更改文本

mysql - 错误: Can't set headers after they are sent.(jwt身份验证)

javascript - 通过 Node.js 连接到 OpenVPN 服务器

python - Facebook 登录使用请求错误

ruby-on-rails - Rails 中的线程 - params[] 是否持续存在?

javascript - Angular 5 服务正在从 api 返回数据,但组件没有向我显示数据