Nest.JS test EventEmitter Handler with Jest
18:13 10 Nov 2022

I'm developing a backend API with Nest.JS which works great so far.

Recently I added tests with Jest and it works good.

However, I came across a problem and I do not understand how to solve this issue.

I use EventEmitter2 to emit and handle events. So basically on a service function, I do some action on the database and emit a custom event afterwards, so another handler can do something.

This works like a charm, when I call the API. However, it does not work inside the test environment.

I don't get any errors, everything seems to work, but the event is not being consumed somehow, when inside the test (console.log is not appearing, but when called from "outside" API call it works as expected).

// the same test function calls the function that will emit an event
// i add delay to ensure the event can be consumed in the meantime
jest.setTimeout(30000);
  it('should contain metadata', async () => {
    await new Promise((r) => setTimeout(r, 5000));
    const response = await controller.findAll(testAccount);
    // it should contain metadata, but it is still undefined, so event is not consumed

This is the test setup:

beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        EventEmitterModule.forRoot(),
        MyModule,
        //..
      ],
    }).compile();

this.eventEmitter.emit('event', { data });

// the consumer
@OnEvent('event')
  async handleEvent

jestjs nestjs nest eventemitter