如何模拟Node.js child_process生成函数?

时间:2014-11-10 08:53:41

标签: 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调用并让我指定模拟调用的输出?

我不想依赖工具或操作系统来保持测试简单和孤立。我希望能够运行测试而无需设置复杂的测试夹具,这可能意味着很多工作(包括更改系统配置)。

有一种简单的方法吗?

4 个答案:

答案 0 :(得分:5)

您可以使用 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

答案 1 :(得分:4)

我找到了mock-spawn库,它几乎可以满足我的需求。它允许模拟spawn调用并将预期结果提供给调用测试。

一个例子:

var mockSpawn = require('mock-spawn');

var mySpawn = mockSpawn();
require('child_process').spawn = mySpawn;

mySpawn.setDefault(mySpawn.simple(1 /* exit code */, 'hello world' /* stdout */));

可在项目页面上找到更多高级示例。

答案 2 :(得分:2)

遇到这个,nwinkler的回答让我走上了正轨。下面是一个Mocha,Sinon和Typescript示例,它将spawn包装在promise中,如果退出代码为零则解析,否则拒绝,它收集STDOUT / STDERR输出,并允许您通过STDIN管道文本。测试失败只是测试异常的问题。

function spawnAsPromise(cmd: string, args: ReadonlyArray<string> | undefined, options: child_process.SpawnSyncOptions | undefined, input: string | undefined) {
    return new Promise((resolve, reject) => {
        // You could separate STDOUT and STDERR if your heart so desires...
        let output: string = '';  
        const child = child_process.spawn(cmd, args, options);
        child.stdout.on('data', (data) => {
            output += data;
        });
        child.stderr.on('data', (data) => {
            output += data;
        });
        child.on('close', (code) => {
            (code === 0) ? resolve(output) : reject(output);
        });
        child.on('error', (err) => {
            reject(err.toString());
        });

        if(input) {            
            child.stdin.write(input);
            child.stdin.end();
        }
    });
}

// ...

describe("SpawnService", () => {
    it("should run successfully", async() => {
        const sandbox = sinon.createSandbox();
        try {
            const CMD = 'foo';
            const ARGS = ['--bar'];
            const OPTS = { cwd: '/var/fubar' };

            const STDIN_TEXT = 'I typed this!';
            const STDERR_TEXT = 'Some diag stuff...';
            const STDOUT_TEXT = 'Some output stuff...';

            const proc = <child_process.ChildProcess> new events.EventEmitter();
            proc.stdin = new stream.Writable();
            proc.stdout = <stream.Readable> new events.EventEmitter();
            proc.stderr = <stream.Readable> new events.EventEmitter();

            // Stub out child process, returning our fake child process
            sandbox.stub(child_process, 'spawn')
                .returns(proc)    
                .calledOnceWith(CMD, ARGS, OPTS);

            // Stub our expectations with any text we are inputing,
            // you can remove these two lines if not piping in data
            sandbox.stub(proc.stdin, "write").calledOnceWith(STDIN_TEXT);
            sandbox.stub(proc.stdin, "end").calledOnce = true;

            // Launch your process here
            const p = spawnAsPromise(CMD, ARGS, OPTS, STDIN_TEXT);

            // Simulate your program's output
            proc.stderr.emit('data', STDERR_TEXT);
            proc.stdout.emit('data', STDOUT_TEXT);

            // Exit your program, 0 = success, !0 = failure
            proc.emit('close', 0);

            // The close should get rid of the process
            const results = await p;
            assert.equal(results, STDERR_TEXT + STDOUT_TEXT);
        } finally {
            sandbox.restore();
        }
    });
});

答案 3 :(得分:1)

对于仍然因特定原因而仍然存在问题且由于某些原因仍然无法解决其他问题的人,我能够通过proxyrequirehttps://github.com/thlorenz/proxyquire)用事件发射器替换真正的child_process生成物,然后在测试中使用它来模拟发射。

var stdout = new events.EventEmitter();
var stderr = new events.EventEmitter();
var spawn = new events.EventEmitter();
spawn.stderr = stderr;
spawn.stdout = stdout;

var child_process = {
  spawn: () => spawn,
  stdout,
  stderr
};

// proxyrequire replaces the child_process require in the file pathToModule
var moduleToTest = proxyquire("./pathToModule/", {
  'child_process': child_process
});

describe('Actual test', function () {
  var response;

  before(function (done) {
    // your regular method call
    moduleToTest.methodToTest()
    .then(data => {
      response = data;
      done();
    }).catch(err => {
      response = err;
      done();
    });

    // emit your expected response
    child_process.stdout.emit("data", "the success message sent");
    // you could easily use the below to test an error
    // child_process.stderr.emit("data", "the error sent");
  });

  it('test your expectation', function () {
    expect(response).to.equal("the success message or whatever your moduleToTest 
      resolves with");
  });
});

希望这对您有帮助...