質問

I am trying to write some CucumberJS features, which will test a NodeJS command line application I am creating, however I am running into problems being able to execute a child_process within a feature step.

Simply to get a proof of concept working I am attempting to execute the ls -l command.

The code that I have is;

var ChildProcess = require('child_process');

function execCmd() {

  console.log('Testing command...');
  var bin = ChildProcess.exec('ls -l', { timeout: 5 }, function(error, stdout, stderr) {
    console.log('executing...');
    console.log(error);
    console.log(stdout);
    console.log(stderr);
  });

  bin.on('exit', function(code) {
    console.log('Code: ' + code);
  });
}

module.exports = function() {

  this.Given(/^I am on the command line$/, function(callback) {
    execCmd();
    callback();
  });

}

Executing cucumber-js does not output anything from the executed command. The output is as follows;

Testing command...
.

1 scenario (1 passed)
1 step (1 passed)

But if I simply call execCmd() after the function definition, removing the module.exports block and run node cli.js I see the output (i.e. the file listing) correctly.

I have seen how to access stdout,stderr, and error in cucumber.js step definition using nodejs child_process exec, which doesn't answer the question and is simply states how to execute a command and nothing specific to running this within a CucumberJS step.

Thanks!

役に立ちましたか?

解決

I believe the issue is due to a couple things:

  1. The callback is invoked in the Given, essentially exiting the cucumberjs program prior to finishing the child process execution.
  2. The exit delegate passed into exec() is being overridden when assigning an 'on' event handler.

I believe this will solve your issue:

var ChildProcess = require('child_process');

function execCmd(cb) {

  console.log('Testing command...');
  var bin = ChildProcess.exec('ls -l', {timeout:5}, function(error, stdout, stderr) {
    console.log('executing...');
    console.log(error);
    console.log(stdout);
    console.log(stderr);
    cb();
  });
}

module.exports = function() {

  this.Given(/^I am on the command line$/, function(callback) {
    execCmd(callback);
  });

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top