Node.js e2e test for endpoint with async task that is not awaited

Viewed 322

I am developing an API in Node.js (NestJS) and have an endpoint which calls two async services. The first one is awaited and its result returned in the response. The second one is left to run in the background and its status is stored and updated in the database.

Something like this:

  @Post()
  async test(): Promise<CustomResponse> {
    const result = await firstAsyncService();

    this.secondAsyncService(result);

    return result;
  }

What is the usual approach to writting e2e tests in situations like this? I am using jest and so far I just make assertions on the result in my test.

it('test', async () => {
  const response = await request(app.getHttpServer())
   .post('/test')
   .send({});

   expect(response).toEqual(something)
});
1 Answers

You should mock this.secondAsyncService(result) in testing and create separate tests for it.

Also leaving promises unhandled is not good approach, consider to rewrite this enpoint and use some cron to make hard work and maybe rabbitMQ to handle comunication.

Related