Search code examples
node.jsgulpmocha.jssinonchild-process

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


I'm testing a gulp plugin that uses child_process.spawn and I'm trying to spy on spawn so I can return an error. With sinon, I've tried used .returns and .throws with no success.

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();
  });
});

Solution

  • I forgot to stub the child process that spawn 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);