Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
Jest mock event emitters vanilla JS in Node.js

I have a class with a method which emits an event on completion. I'm trying to get as much test coverage as possible on said class, and I can't work out how to mock events from inside a class method properly.

Stub:

class Broker extends EventEmitter {
    constructor(socket, stateMachine) {
        if (socket == undefined || stateMachine == undefined) {
            throw new Error("Insufficient constructor arguments.");
        }
        super();
        this.socket = socket;
        this.stateMachine = stateMachine;
    }

    /* ... */
    parseHeaderOnceRead() {
        this.header = Buffer.alloc(32);
        /* Parse data here */
        this.emit('headerParsed', this.header);
    }
}

Then in my Broker.test.js file, I'm completely lost on how I test the event emitter. Every guide I can find all use frameworks or dialects (Typescript, Angular, Vue) none I can find seem to use vanilla JS. I've tried two SO solutions, this one I've spent most time on:

[solution 1] (Mock a custom event emitter with jest)

My test file looks something like this:

const { Broker } = require("../../socketBroker");
let testBroker = new Broker('Fake Socket', {});

let commonEmitterMock;

beforeEach(() => {
    commonEmitterMock = createMock('emit');
});

test('Check that events are emitted properly', ()=> {
    const method = testBroker.parseHeaderOnceRead();
    expect(commonEmitterMock).toHaveBeenCalledWith('headerParsed');
});

But I'm receiving the following error:

 FAIL  __tests__/SocketBroker/ParseHeaderOnceRead.test.js
  ✕ Check that events are emitted properly (1 ms)

  ● Check that events are emitted properly

    ReferenceError: createMock is not defined

       5 |
       6 | beforeEach(()=> {
    >  7 |     commonEmitterMock = createMock('emit');
         |     ^
       8 | });
       9 |
      10 | test('Check that events are emitted properly', ()=> {

      at Object.<anonymous> (...)

I'm running WSL on Windows 10 latest build, Node 16.6.1, Jest 27.2.0 (installed globally rather than as a dependency). I've tried reading the Jest docs but cannot find a reference to event emitters anywhere :/

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda