在Mocha测试中响应NodeJS提示

时间:2015-05-05 19:09:51

标签: node.js unix mocha

我正在尝试在Mocha中为我编写的命令行NodeJS应用程序编写一些测试。

Node应用程序将提示用户输入URL。然后它获取URL,为CSS,JS和Image文件解析它,并将它们下载到各自的目录中。

我无法获得测试设置,因为应用程序依赖于用户输入,我无法弄清楚如何以编程方式将键击发送回提示符。

我在Node应用程序功能中的URL请求基本上是这样的:

rl.setPrompt('Please enter URL: ');
  rl.prompt();
  rl.on('line', function(line) {
    url = line;
    rl.close();
  }).on('close', function(){
    request(url, function (error, response, body) {
      if (!error) {
        /* Do some stuff here */
      } else {
        throw new Error('Err making initial HTTP request. Attempted: '+url);
        return false;
      }
    });
  });

我的测试目前看起来像

var child = require('child_process');
var assert = require("assert");


describe('System', function(){
  before(function(){

  });
  it('should run successfully', function(){
    child.execSync('node index.js', function(error, stdout, stderr){
      //console.log(stdout);
    });
  });
});

测试电流立即失败,因为它在没有用户输入的情况下无法运行。这可能是同步的吗?我找不到任何关于如何等待并回应提示的内容。

1 个答案:

答案 0 :(得分:4)

您需要提取一个可以实际测试的函数。所以看起来应该是这样的:

rl.setPrompt('Please enter URL: ');
rl.prompt();
rl.on('line', function(line) {
  url = line;
  rl.close();
}).on('close', function(){
  parseUrl(url); 
  });
});

...

function parseUrl(url){
  request(url, function (error, response, body) {
    if (!error) {
      /* Do some stuff here */
    } else {
      throw new Error('Err making initial HTTP request. Attempted: '+url);
      return false;
    }
}

现在你有一个小功能parseUrl,你可以很容易地测试它。只需传递测试网址即可。