How to mock the Node.js child_process spawn function?

nwinkler picture nwinkler · Nov 10, 2014 · Viewed 6.9k times · Source

Is there an easy way to mock the Node.js child_process spawn function?

I have code like the following, and would like to test it in a unit test, without having to rely on the actual tool calls:

var output;
var spawn = require('child_process').spawn;
var command = spawn('foo', ['get']);

command.stdout.on('data', function (data) {
    output = data;
});

command.stdout.on('end', function () {
    if (output) {
        callback(null, true);
    }
    else {
        callback(null, false);
    }
});

Is there a (proven and maintained) library that allows me to mock the spawn call and lets me specify the output of the mocked call?

I don't want to rely on the tool or OS to keep the tests simple and isolated. I want to be able to run the tests without having to set up complex test fixtures, which could mean a lot of work (including changing system configuration).

Is there an easy way to do this?

Answer

gaozhidf picture gaozhidf · Sep 16, 2017

you can use sinon.stubs sinon stubs guide

// i like the sandbox, or you can use sinon itself
let sandbox = sinon.sandbox.create();

let spawnEvent = new events.EventEmitter();
spawnEvent.stdout = new events.EventEmitter();

sandbox.stub(child_process, 'spawn').returns(spawnEvent);

// and emit your event
spawnEvent.stdout.emit('data', 'hello world');

console.log(output)  // hello world