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?
I've found the mock-spawn library, which pretty much does what I want. It allows to mock the spawn
call and provide expected results back to the calling test.
An example:
var mockSpawn = require('mock-spawn');
var mySpawn = mockSpawn();
require('child_process').spawn = mySpawn;
mySpawn.setDefault(mySpawn.simple(1 /* exit code */, 'hello world' /* stdout */));
More advanced examples can be found on the project page.