Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda