Spying on stdout of stdio: inherit spawn process

Viewed 50

Have a simple function I'm trying to unit test:

const {spawn} = require('child_process');

function exec (command, args) {
  return spawn(command, args, {
    stdio: `inherit`
  });
}

Since this is using inherit, echo.stdout.on will not work, though I would presume that with the stdio being shared with the parent process, and the parent process presumably being the running script, that I could just override process.stdout.write (or console.log), but this did not work (neither did overwriting global.process.stdout.write). How can I spy on write using the above exec with the following not working?


let str = '';
const {write} = process.stdout;
process.stdout.write = (s) => {
  str += s; // Does not run
};
const echo = exec('echo', ['hello', 'world']);
echo.on('exit', () => {
  process.stdout.write = write;
  throw (new Error('Result ' + str));
});
setTimeout(() => {
  echo.kill();
}, 1000);
0 Answers
Related