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 :/