How to fix err Jest has detected the following 3 open handles potentially keeping Jest from exiting

detectOpenHandles option is used to detect open handles, it should be normally used. The error warns about potentially open handles:

Jest has detected the following 4 open handles potentially keeping Jest from exiting

Even if the handles will be closed, the error will still appear.

The actual problem with this application is that database connection isn't really closed:

if (process.env.NODE_ENV === 'test') {
  mongoose.connection.close(function () {
    console.log('Mongoose connection disconnected');

For some reason NODE_ENV is dev, despite that the documentation states that it's expected to be test.

Closing database connection immediately on application start may cause problems in units that actually use database connection. As explained in the guide, MongoDB connection should be at the end of test. Since default Mongoose connection is used, it can be:

afterAll(() => mongoose.disconnect());

Here's what I did to solve this problem.

    afterAll(async () => {
  await new Promise(resolve => setTimeout(() => resolve(), 10000)); // avoid jest open handle error

Then I set jest.setTimeout in the particular test that was giving issues.

describe('POST /customers', () => {
  test('It creates a customer', async () => {
    const r = Math.random()
    const response = await request(server)
        name: r,
        email: `${r}@${r}.com`,
        password: 'beautiful',
    // console.log(response.body);

As answered above, close any other open handles.