如何使用 sinon 从节点流中存根错误?

How can I stub an error from a node stream using sinon?

我正在测试一个使用 child_process.spawn 的 gulp 插件,我正在尝试监视 spawn 以便 return 出错。对于 sinon,我尝试使用 .returns 和 .throws 但没有成功。

index.js
--------
const cp = require('child_process');
const PluginError = require('plugin-error');
const through = require('through2');

module.exports = () => {
  return through.obj(function (file, enc, cb) {
    const convert = cp.spawn('convert');

    convert.on('error', (err) => {
      cb(new PluginError(PLUGIN_NAME, 'ImageMagick not installed'));
      return;
    });
  });
}

test.js
-------
const cp = require('child_process');
const expect = require('chai').expect;
const plugin = require('../index');
const sinon = require('sinon');
const Vinyl = require('vinyl');

it('error when ImageMagick not installed', (done) => {
  sinon.stub(cp, 'spawn'); // Problem area: I tried .returns and .throws
  const vinyl = new Vinyl();

  const stream = plugin();
  stream.write(vinyl);
  stream.once('error', (error) => {
    expect(error);
    done();
  });
});

我忘了存根生成的子进程 returns!

let mockProcess = {
  on: sinon.stub(),
  stdout: {
    on: sinon.stub()
  },
  stderr: {
    on: sinon.stub()
  }
};
mockProcess.on.withArgs('error').yieldsAsync(new Error());
sinon.stub(cp, 'spawn').returns(mockProcess);