@push-based/node-cli-testing
Version:
### A e2e-testing library for node CLI and processes including sandbox generation on the fly
67 lines (66 loc) • 2.16 kB
JavaScript
;
exports.__esModule = true;
exports.testProcessE2e = void 0;
// @ts-ignore
var concat = require("concat-stream");
var fs = require("fs");
var execa = require("execa");
/**
* A function to control a process and its in and outputs.
* Starts a node process with a given configuration Takes parameters
*
* @param args
* parameters passed to the process
* @param answers
* values to be passed to process
* @param options
* specify the process configuration
* @param promptOptions
* specify the process configuration
*/
function testProcessE2e(args, answers, options, promptOptions) {
// Defaults to process.cwd()
if (args === void 0) { args = []; }
if (answers === void 0) { answers = []; }
if (options === void 0) { options = {}; }
if (promptOptions === void 0) { promptOptions = {}; }
// validate input
if (!fs.existsSync(options.cwd + '')) {
throw new Error("cwd ".concat(options.cwd, " does not exist."));
}
if (!fs.existsSync(args[0])) {
throw new Error("bin file ".concat(args[0], " does not exist."));
}
// Timeout between each keystroke simulation
var timeout = promptOptions && promptOptions.timeout ? promptOptions.timeout : 500;
var runner = execa('node', args, options);
runner.stdin.setDefaultEncoding('utf-8');
var writeToStdin = function (answers) {
if (answers.length > 0) {
setTimeout(function () {
runner.stdin.write(answers[0]);
writeToStdin(answers.slice(1));
}, timeout);
}
else {
runner.stdin.end();
}
};
// Simulate user input (keystrokes)
writeToStdin(answers);
return new Promise(function (resolve) {
var obj = {};
runner.stdout.pipe(concat(function (result) {
obj.stdout = result.toString();
}));
runner.stderr.pipe(concat(function (result) {
obj.stderr = result.toString();
}));
runner.on('exit', function (exitCode) {
obj.exitCode = exitCode;
resolve(obj);
});
});
}
exports.testProcessE2e = testProcessE2e;
;