Paul Sanwald Paul Sanwald - 1 year ago 151
Javascript Question

How to mock an EventEmitter on `createReadStream`?

I'm trying to write a test case for when an error is emitted as a result of this code:

Bucket: mediaBucket,
Key: mediaId,

I've got a test with a dummy S3 object, and I'm using MemoryStream to cover cases where the call is successful. How do I emit an error, so I can write a test that allows me to test the behavior in
.on('error') function(error)..

Here's what I've tried, without success:

beforeEach(function () {
var emitter = new EventEmitter;
const s3 = {
getObject: () => {
return { createReadStream: () => emitter.emit('error', new Error('Random error!')) }

Answer Source

Just emit it like you would any other event:

stream.emit('error', new Error('Random error!'));

So, the above code should look like:

const s3 = {
  getObject: () => {
    return { createReadStream: () => {
      process.nextTick(function() {
        emitter.emit('error', new Error('whoops!'));
      return emitter;
    } }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download