首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >superagent和nock如何协同工作?

superagent和nock如何协同工作?
EN

Stack Overflow用户
提问于 2013-02-04 22:50:37
回答 1查看 4.1K关注 0票数 16

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

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

代码语言:javascript
复制
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对象没有'text‘属性。出了点问题。

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

代码语言:javascript
复制
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,所以我更愿意坚持使用它。有谁知道怎么让它工作吗?

谢谢你,泽维尔

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-04 23:59:56

我的假设是,既然您使用{yes: 'it works'}进行响应,那么Nock将以application/json作为mime类型进行响应。请看Superagent中的res.body。如果这个不起作用,请让我知道,我会仔细看看。

编辑:

试试这个:

代码语言:javascript
复制
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
});

或者..。

代码语言:javascript
复制
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类型时,superagent知道如何处理application/json,以及为什么可以使用res.textres.body (解析的JSON)。

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14689252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档