stub an event emitter and listener with sinon in javascript

To stub an Event Emitter and Listener with Sinon in JavaScript, you can follow these steps:

  1. Install Sinon in your project by running npm install --save-dev sinon.

  2. Require Sinon in your test file by adding the following line at the top of your file: const sinon = require('sinon');.

  3. Create a stub object using sinon.createStubInstance method, passing in the class of the EventEmitter:

index.tsx
const EventEmitter = require('events').EventEmitter;
const stub = sinon.createStubInstance(EventEmitter);
106 chars
3 lines
  1. Create a listener function and register it with the event emitter like this:
index.tsx
const listener = sinon.stub();
stub.on('event', listener);
59 chars
3 lines
  1. Emit the event from the stubbed EventEmitter like this:
index.tsx
stub.emit('event', 'some', 'arguments');
41 chars
2 lines
  1. Verify that the listener was called with the correct arguments: sinon.assert.calledWith(listener, 'some', 'arguments');

Here is an example of a full test suite with a stubbed EventEmitter and listener:

index.tsx
const sinon = require('sinon');
const EventEmitter = require('events').EventEmitter;

describe('EventEmitter', () => {
  it('should emit the event with the correct arguments', () => {
    const stub = sinon.createStubInstance(EventEmitter);
    const listener = sinon.stub();
    stub.on('event', listener);

    stub.emit('event', 'some', 'arguments');

    sinon.assert.calledWith(listener, 'some', 'arguments');
  });
});
425 chars
15 lines

By following these steps, you can stub and test your Event Emitters and Listeners in your JavaScript application.

gistlibby LogSnag