16

node.jsで、スーパーエージェントとノックを連携させるのに問題があります。スーパーエージェントの代わりにリクエストを使用すると、完全に機能します。

スーパーエージェントがモックデータの報告に失敗する簡単な例を次に示します。

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)
  }
})

モックされたコンテンツは正しく表示されます。

テストではスーパーエージェントを使用したので、それを使い続けたいと思います。誰かがそれを機能させる方法を知っていますか?

どうもありがとう、ザビエル

4

1 に答える 1

13

私の推測ではapplication/json、あなたがで応答しているので、Nockはmimeタイプとして応答しています{yes: 'it works'}。スーパーエージェントで見てください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。その場合、スーパーエージェントはメモリを節約するために応答をバッファリングしません。あなたはそれをバッファリングするように強制しなければなりません。そのため、HTTPサービスがとにかく必要なmimeタイプを指定すると、スーパーエージェントは何を処理するかを認識し、または(解析されたJSON)application/jsonのいずれかを使用できるかどうかを認識します。res.textres.body

于 2013-02-04T15:59:56.170 に答える