在node.js中,我很难让superagent和nock一起工作。如果我使用request而不是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);
});res对象没有'text‘属性。出了点问题。
现在,如果我使用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)
}
})模拟的内容将正确显示。
我们在测试中使用了superagent,所以我更愿意坚持使用它。有谁知道怎么让它工作吗?
谢谢你,泽维尔
发布于 2013-02-04 23:59:56
我的假设是,既然您使用{yes: 'it works'}进行响应,那么Nock将以application/json作为mime类型进行响应。请看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类型时,superagent知道如何处理application/json,以及为什么可以使用res.text或res.body (解析的JSON)。
https://stackoverflow.com/questions/14689252
复制相似问题