nodejs让xml什么也没有返回

时间:2014-10-20 22:16:51

标签: node.js mocha

我正在尝试下载一个xml文件,以便我可以在nodejs中解析它。这是我通过mocha构建的测试,测试通过,但控制台上没有任何内容。我做错了什么?

it('Get XML data', function() {
var options = {
      hostname: 'stona-app01.us.work.net',
      port: 1213,
      path: '/solrLive/STONA-STOUS-product-search-idx-en_US/select/?version=2.2&start=2&rows=2&qf=SKU&fl=*&indent=on&onlineFlag=1',
      method: 'POST'
    };

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

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

代码中的网址无法访问,因此您无法对其进行测试。

1 个答案:

答案 0 :(得分:0)

您的测试是异步的,因此您必须定义测试以获取done参数并在测试完成后调用它:

it('Get XML data', function (done) {
   var options = {
      hostname: 'stona-app01.us.work.net',
      port: 1213,
      path: '/solrLive/STONA-STOUS-product-search-idx-en_US/select/?version=2.2&start=2&rows=2&qf=SKU&fl=*&indent=on&onlineFlag=1',
      method: 'POST'
    };

    var req = http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        done(); // We're done!
      });
    });

    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
      done(e); // Pass the error to Mocha.
    });
});