0

我在玩誓言和nodejs。

var vows = require('vows');
var http = require('http');
var suite = vows.describe('testing');
var host = 'www.google.com', port = '80', path = '/', method = 'GET';

suite.addBatch({
    'A context': {
        topic: function(){
            http.get({
              host: host,
              port: port,
              path: path,
              method: method
            }, this.callback);
        },
        "sample test": function(res, extra){//here extra is just to prevent vows error
            res.on('data', function (chunk) {
                console.log('BODY: ' + chunk);//It never gets logged
            });
            console.log('HEADERS: ' + JSON.stringify(res.headers));//it is working
        }
    }
});

suite.export(module);

但我无法获得响应正文。我究竟做错了什么。

我正在使用 nodejs v 0.6.6 和 vows v0.6.2

4

1 回答 1

1

从我所见,看起来 Vows 在this.callback运行时并没有直接调用测试。它被延迟processnextTick。如果我不得不猜测,也许在那段时间正在发出“数据”事件。这意味着在所有数据事件被触发之前,您不会绑定您的“数据”函数。

但实际上,问题在于 Vows 测试应该将所有像这样的异步逻辑分离到topic自身中。如果你真的想在测试中检查块,那么就这样做。

另请注意,您可以拥有任意数量的块,而不仅仅是一个data事件。您可能想要设置流编码,并将数据连接为字符串。您当前的代码将 Buffer 隐式转换为字符串,这可能会因多字节字符而中断。

suite.addBatch({
    'A context': {
        topic: function(){
            var cb = this.callback;
            var req = http.get({
              host: host,
              port: port,
              path: path,
              method: method
            });

            // Aggregate all chunks before running callback
            req.on('response', function(res) {
              var chunks = []
              res.on('data', function(chunk) {
                chunks.push(chunk);
              });
              res.on('end', function() {
                cb(null, res, chunks);
              });
            });

            // Handle connection failures.
            req.on('error', cb);
        },
        "sample test": function(err, res, chunks){
            chunks.forEach(function (chunk, i) {
                console.log('BODY piece ' + i + ': ' + chunk);
            });
            console.log('HEADERS: ' + JSON.stringify(res.headers));
        }
    }
});
于 2012-05-05T18:41:42.943 回答