Nodejs Integration testing fire and forget testing

Viewed 84

I have a function controller which does some DB updates and inserts.

Example

export const patchRecords = async (req: Request, res: Response) => {
    // Do some inserts.
    // Do some work.
       res.sendStatus(200);
    //fire and forget
    await additionalUpdate();
}

While testing this function I am getting some issues. The error is obvious but I am unable to fix this.

The error is that, the jest environment is already torn down once the sendStatus expect passes.

example test:

  it.only('should insert order for store and product.', async () => {

        const { status } = await jsonApiRequest(
            'POST',
            `${baseUrl}/updateproducts/${storeNumber}/${productId}`,
            {
                accessToken,
            }
        );
      expect(status).toBe(201)
    });

The test passes, but I get below error:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log "Failed sql and bindings 

This happens because of the fire and forget function which is called after sendStatus

 await additionalUpdate(); // is heavy function takes some time to complete

I tried adding a delay in the test, but it will not work, because the we cannot predict time taken by additionalUpdate to complete.

        delay(()=> {
            expect(status).toBe(201)
        }, 1000);

I tried mocking the additionalUpdate function but that too does not work as it's integration test.

How can I fix this?

0 Answers
Related