0

http.Serverrequest イベント(つまり、 signature を持つ関数) のハンドラーを作成しましfunction (request, response) { ... }た。これをテストしたいと思います。http.ServerRequestモックとhttp.ServerResponseオブジェクトを介してこれを行いたいと思います。これらを作成するにはどうすればよいですか?

明らかな方法はうまくいかないようです:

$ node
> var http = require('http');
> new http.ServerRequest();
TypeError: undefined is not a function
    at repl:1:9
...

「実際の」HTTP サーバーとクライアントを介してこれをテストする必要がありますか?

4

3 に答える 3

3

http.ServerRequestandのモックを許可するプロジェクトが少なくとも 2 つありますhttp.ServerResponse: https://github.com/howardabrams/node-mocks-httphttps://github.com/vojtajina/node-mocks

そして、何らかの理由で、実際の HTTP リクエストを介してテストする方が一般的であるようです。https://github.com/flatiron/nockは、ここで使用するツールのようです。

node.js: モック http リクエストとレスポンスも参照してください。

于 2013-02-25T13:50:51.137 に答える
0

はい、http.requestを使用して実行できます。サーバーからリクエストを発行できるため、コードでテストできます。単純な GET リクエストを送信したい場合は、より簡単なhttp.getを使用できます。それ以外の場合は、自分でリクエストを作成する必要があります。ドキュメントの例:

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  res.setEncoding('utf8');
  console.log('STATUS: ' + res.statusCode);
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.write('data\n');
req.end();

requestを使用している場合は、同じことができます。

var request = require('request');
request.post( url, json_obj_to_pass,
    function (error, response, body) {
        if (!error && response.statusCode == 200)
            console.log(body)
    }
);
于 2013-02-22T16:03:45.020 に答える