3

My setup uses chai, sinon, chai-sinon, chai-as-promised, babel and es6 syntax.

I have the following (reduced) code

// example.js
'use strict';
import EventEmitter from 'events';

class Dispatcher extends EventEmitter {
  send(x) {
    doSomethingAsync() // promise is NOT returned 
      .then(() => {
        this.emit('sent');
      })
      .catch((err) => {
        this.emit('error', err);
      });
  }
}

Note: the promise from doSomethingAsync is NOT returned. (And never will be)

Here's my (reduced) test file

let dispatcher;
let onSent;
let onError;

beforeEach(() => {
  dispatcher = new Dispatcher();

  onSent = sinon.stub();
  onError= sinon.stub();
  dispatcher.on('sent', onSent);
  dispatcher.on('error', onError);
});

describe('send', () => {
  it('should emit "error" on sendFn error instead of "sent"', () => {
    ... set up state for failure ...
    dispatcher.send(...);
    ... What do I do here or how do I wrap the following? ...
    expect(onSent).not.to.have.been.called;
    expect(onError).to.have.been.called;
  });
});

I know how to do this if I could return the promise from doSomethingAsync as the result of send, but that's not the case here. All I have is the knowledge that either the 'sent' or 'error' event will be emitted eventually.

My ideal syntax would look like:

expect(onError).to.eventually.have

But, that doesn't work. I CAN get a non-erroring version to work as follows simply by wrapping the expect in a new promise. But I have no idea why this works.

  // This one works for some unknown reason!
  it('should emit "send" on send success', () => {
    ... set up state for success ...
    dispatcher.send(...);
    return Promise.resolve().then(() => {
       expect(onSent).to.have.been.called;
       expect(onError).not.to.have.been.called;
    });     
  });

If I could refactor the code in such a way as to expose the inner promise, then this would be trivial to solve. I have done so countless times in other circumstances. My question here however is very specifically how to solve this exact pattern; i.e. how to test the side-effects of an inaccessible promise or async code, particularly around event emitters when I cannot refactor the code to expose the promise.

I have tried at least the following just to see if I could trigger the desired send function to complete all its inner callbacks/promises before the test calls the expectations

  • wrapping the expectations in a promise
  • controlling time using sinon.useFakeTimers
  • wrapping the expectations in a timeout
  • wrapping both send call and expectations in various async/await patterns

Thanks in advance.

EDIT:

Ok, so this is completely ridiculous, but here's a solution that works for both resolved and rejected promises:

it('should behave as expected already!', (done) => {
  ... set up for failure or success as desired
  dispatcher.send();
  process.nextTick(() => {
    Promise.resolve().then(() => {
      ... expectations ...
      done();
    });
  });
});

I think this works because (and I'm totally guessing here!) I assume that thrown errors or rejected promises are processed immediately in the current tick, whereas resolved promises get queued in the next tick. So... the process.nextTick ensures that we will queue this function in the next tick, allowing all catches/errors to complete, and the Promise.resolve ensures that it is queued after any already-queued promises are run. Incidentally, you can also switch the order or the nextTick and promise.resolve() and it works just fine.

NB If the events are emitted truly asynchronously (e.g. in their own process.nextTick then you have to have a 3-level nest. Either Promise-nextTick-promise or nextTick-promise-nextTick.

My word that is messy!

... still better than timeouts though :D

0

2 Answers 2

2

Since the tests are not waiting for the block of code you are testing to resolve/reject the promise, assertions won't work.

And your analysis are all correct but the approach to solve is to resolve promise in assertions.

I have made some changes to your code and made it working.

I have made doSomethingAsync to return the promise (I think that is the right solution here)

// Code to be tested

import EventEmitter from 'events';

const doSomethingAsync = async (x) => {
  return x;
};

class Dispatcher extends EventEmitter {
  send(x) {
    return doSomethingAsync(x)
      .then((res) => {
         this.emit('sent');
      })
      .catch((err) => {
         this.emit('error', err);
      });
  }
}

export default Dispatcher;

// Tests

Option 1: Using await

import sinon from 'sinon';
import { expect } from 'chai';
import Dispatcher from '../dispatcher';

describe('send', () => {
  let dispatcher;
  let onSent;
  let onError;

  beforeEach(() => {
    dispatcher = new Dispatcher();
    onSent = sinon.stub();
    onError = sinon.stub();
    dispatcher.on('sent', onSent);
    dispatcher.on('error', onError);
  });

  it('Test 1: should emit "error" on sendFn error instead of "sent"', async () => {
    await dispatcher.send('hello');
    expect(onSent.callCount).to.equal(1);
    expect(onError.callCount).to.equal(0);
  });
});

// Result

yarn run spec

send ✓ should emit "error" on sendFn error instead of "sent"

1 passing (1s)

✨ Done in 4.18s.

Option 2: With promises

In the test, you can see that I am using an await on dispatcher.send or you could also assert using promises as below

it('Test 2: should emit "error" on sendFn error instead of "sent"', () => {
  let error = false;
  dispatcher.send('hello').then(() => {
    expect(onSent.callCount).to.equal(1);
    expect(onError.callCount).to.equal(0);
  }).catch(() => {
    error = true;
  })
  expect(error).to.equal(false);
});

PS:- If you don't wish to return promise, then first test case (the one using await) will pass & second one will fail.

0

Building upon the answer given by anoop, you could do something like this:

function sinonSetUp( eventEmitter )
{
    let onSent = sinon.stub();
    let onError = sinon.stub();
    eventEmitter.on( 'sent', onSent );
    eventEmitter.on( 'error', onError );
    return ({
        onSent: onSent,
        onError: onError,
    });
}

it('emits a sent event', async function()
{
    let dispatcher = new Dispatcher();
    let sinonHandlers = sinonSetUp(dispatcher);
    let promise = dispatcher.send();
    await promise;

    //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    //Checking the error event:
    //The way you wish you could do it:
    /* 
    dispatcher.on('error', function(errEventVal)
    {
        expect(errEventVal).to.be.undefined; 
    }); 
    */

    //The way you have to do it:
    //args[0] gets the returned arguments, if any exist
    let errEventArgs = sinonHandlers.onError.args[0]; 
    expect(errEventArgs).to.be.undefined;

    //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    //Checking the sent event:
    //The way you wish you could do it:
    /* 
    dispatcher.on('sent', function(sentEventVal)
    { 
        expect(sentEventVal).not.to.be.undefined; 
    }); 
    */

    //The way you have to do it:
    //If args[0] exists, then the value will be in args[0][0]
    //See the documentation for sinonjs.
    let sentEventArgs = sinonHandlers.onSent.args[0];
    expect(sentEventArgs).not.to.be.undefined;
    let sentEventVal = sentEventArgs[0];
    expect(sentEventVal).not.to.be.undefined;
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.