superagent和nock怎么能一起工作?
在node.js中,我很难使superagent和nock一起工作。 如果我使用请求,而不是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”属性。 出了些问题。
现在,如果我使用请求做同样的事情:
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) } })
嘲笑的内容显示正确。
我们在testing中使用了superagent,所以我宁愿坚持下去。 有谁知道如何使其工作?
谢谢,泽维尔
我的推测是,Nock是作为MIMEtypes的application/json
响应,因为你用{yes: 'it works'}
回应。 在res.body
看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不设置MIMEtypes,并且默认是假定的。 我假设默认是application/octet-stream
。 如果是这样的话,superagent就不会缓冲响应来节省内存。 你必须强制它缓冲它。 这就是为什么如果你指定一个MIMEtypes,你的HTTP服务应该反正,superagent知道如何处理application/json
以及为什么如果你可以使用res.text
或res.body
(parsing的JSON)。