在node.js中,我很难使超级代理和nock协同工作。如果我使用request而不是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"属性。出了问题。
现在,如果我使用请求做同样的事情:
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)
}
})
模拟内容显示正确。
我们在测试中使用了超级试剂,所以我宁愿坚持使用。有人知道如何使它发挥作用吗?
非常感谢,Xavier
我的假设是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
。如果是这种情况,那么超级代理就不会缓冲响应以节省内存。你必须强制它缓冲它。这就是为什么如果你指定了一个mime类型,你的HTTP服务无论如何都应该这样做,超级代理知道如何处理application/json
,以及为什么你可以使用res.text
或res.body
(解析的JSON)。