title: Stub a ES6 EventEmitter class function
body: <p>I have a dependency class that extends EventEmitter and I need to test how a function that uses this dependency will react based on the events that it fires. How do you stub a function of a EventEmitter class?</p>
  
  <p><strong>Dependency Class</strong></p>
  
  <pre><code>const EventEmitter = require('events');
  
  class FooBar extends EventEmitter {
  
    constructor() {
      super();
  
      this.doingSomething = false;
    }
  
    doSomething() {
      if (this.doingSomething === false) {
        this.doingSomething = true;
        this.emit('startedDoingSomething');
      }
      else {
        this.emit('alreadyDoingSomething');
      }
    }
  }
  
  module.exports = FooBar;
  </code></pre>
  
  <p><strong>Dependent Module Under Test</strong></p>
  
  <pre><code>let Foobar = require('FooBar');
  let fooBar = new FooBar();
  
  exports.myFunction = () =&gt; {
    // Set up listeners
    fooBar.once('startedDoingSomething', () =&gt; {
      fooBar.removeAllListeners();
      // Some functionality
      console.log('Started Doing Something');
    });
  
    fooBar.once('alreadyDoingSomething', () =&gt; {
      fooBar.removeAllListeners();
      // Some functionality
      console.log('Already Doing Something');
    });
  
    // Call the event-emitting function
    fooBar.doSomething();
  };
  
  // Other functions that use fooBar
  </code></pre>
  
  <p>I'm using Sinon in order to create a stub, but I haven't been able to stub the class functions that emit events effectively. I modeled my test off of <a href="https://github.com/sinonjs/sinon/issues/1045" rel="nofollow noreferrer">[Feature request] stub emits</a> but had to make some modifications since the event emitter dependency being stubbed is a class.</p>
  
  <p><strong>Test</strong></p>
  
  <pre><code>let chai = require('chai');
  let sinon = require('sinon');
  let FooBar = require('FooBar');
  let dependentModule = require('./dependentModule');
  
  describe('Dependent Module', () =&gt; {
    it('alreadyDoingSomething', () =&gt; {
      sinon.stub(FooBar.prototype, 'pause', () =&gt; {
        FooBar.prototype.emit('alreadyDoingSomething');
      });
  
      // Assertion statements here
      expect(dependentModule.myFunction()).to...
    });
  });
  </code></pre>
  
  <p>This approach does not actually emit an event even though the stub function is being called.</p>