How to wait for a function to end using Jest

130 Views Asked by At

I'm using NestJS with Event Emitter, when I do PUT request to /profile, it should emit a profile.update event.

After that, a function will hear it and call an external service to update the profile and end.

So, my e2e test will do a PUT request to /profile and then check with the external service if the profile was updated, but what if the function didn't have time yet to update the profile?

How can I wait the function to ends and then check with the service?

What I tried so far:

 it("shoule be able to notify external service about profile update", async () => {
    const instance = app.get(NotifyExternalServiceAboutProfile);

    const spy = jest.spyOn(instance, 'handle');

    const { body } = await request(app.getHttpServer())
      .post('/profile')
      .send({
        name: 'John Doe'
      })
      .expect(201);

    await request(app.getHttpServer())
      .put('/profile/' + body.id)
      .send({
        name: 'Fulano de tal',
      })
      .expect(200);

    // How can I know if "NotifyExternalServiceAboutProfile" completed? Like a callback.
  });
1

There are 1 best solutions below

0
Thalles Passos On

Solved by myself, I decided to emit an event inside my function mentioned above and then created a Promise which will wait until that event is emitted, then i check the external service.

app.get(EventEmitter2)
new Promise<void>((resolve) => {
  instance.on("profile.externalService", async (event) => {
    // check external service
    resolve();
  });
});