有没有简单的方法来模拟 Node.js child_process spawn
函数?
我有如下代码,并想在单元测试中对其进行测试,而不必依赖实际的工具调用:
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);
}
});
是否有(经过验证和维护的)库允许我模拟 spawn
调用并让我指定模拟调用的输出?
我不想依赖工具或操作系统来保持测试的简单性和独立性。我希望能够运行测试而不必设置复杂的测试装置,这可能意味着很多工作(包括更改系统配置)。
有没有简单的方法来做到这一点?
最佳答案
你可以使用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
关于node.js - 如何模拟 Node.js child_process spawn 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26839932/