node.js - 如何模拟 Node.js child_process spawn 函数?

标签 node.js mocking spawn

有没有简单的方法来模拟 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/

相关文章:

JavaScript:如何将数据添加到 JSON 文件内的数组

node.js - 将 Firebase 的第三方用户数据对象发布到服务器

javascript - 使用 JavaScript 读取在浏览器中打开的页面

go - 如何向数据访问层方法添加测试?

Erlang:带有监视器的生成过程

node.js - MongoDB $lookup 管道匹配 _id 不起作用

php - mock :模拟 publicaly 重写 protected 方法

java - 如何在java protected 方法中测试局部变量

node.js - Node.js 中生成的进程立即退出

erlang - spawn/1 和共享外部变量