Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!