在 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.text
或res.body
(解析的 JSON)。
关于javascript - superagent 和 nock 如何协同工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14689252/