superagent和nock如何一起工作? [英] how can superagent and nock work together?
问题描述
在node.js中,我很难让superagent和nock一起工作。如果我使用请求而不是superagent,它可以很好地工作。
In node.js, I have trouble making superagent and nock work together. If I use request instead of superagent, it works perfectly.
这是一个简单的示例,其中superagent无法报告模拟数据:
Here is a simple example where superagent fails to report the mocked data:
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'属性。出了点问题。
the res object has no 'text' property. Something went wrong.
现在如果我使用请求做同样的事情:
Now if I do the same thing using 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,所以我宁愿坚持下去。有谁知道如何使它工作?
We used superagent in the tests so I'd rather stick with it. Does anyone know how to make it work ?
非常感谢,
Xavier
Thank's a lot, Xavier
推荐答案
我的推测是Nock用 application / json
作为mime类型进行响应,因为你用回复{是:'it works'}
。在Superagent中查看 res.body
。如果这不起作用,请告诉我,我会仔细研究。
My presumption is that Nock is responding with application/json
as the mime type since you're responding with {yes: 'it works'}
. Look at res.body
in Superagent. If this doesn't work, let me know and I'll take a closer look.
编辑:
试试这个:
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)。
Either one works now. Here's what I believe is going on. nock is not setting a mime type, and the default is assumed. I assume the default is application/octet-stream
. If that's the case, superagent then does not buffer the response to conserve memory. You must force it to buffer it. That's why if you specify a mime type, which your HTTP service should anyways, superagent knows what to do with application/json
and why if you can use either res.text
or res.body
(parsed JSON).
这篇关于superagent和nock如何一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!