Jest has detected the following 1 open handle potentially keeping Jest from exiting, points to mongoose's openUri

Viewed 493

My Express.js app uses mongoose to access MongoDB. It uses Jest v27 for unit test.

The app.js file requires the database module:

require('./modules/database/database');

exports.app = app;

The unit tests use this app for testing. Before any test is run, the database.js files connects to two databases. This file contains the following code fragment which is always run when the file is require-ed:

for (const url of urls) {
  const conn = mongoose.createConnection();

  //...

  // Establish connection
  conn.openUri(url, DatabasePrivate.connect_options);

  connections.push(conn);
}

// Wait for connections to complete establishment

(async () => {
  for (const connection of connections) {
    await connection;

    debug('Connection established to %O', connection.db.databaseName);
  }
})();

To close all connections, the database.js module has the following method in Database class:

class Database {
  //...
  static CloseConnections() {
    for (const connection of connections) {
      connection.close();
    }
  }
}

The tests are structured as follows:

const { app } = require('../app');
const { Database } = require('../modules/database/database');

describe('===== Some Tests ===== ', () => {

  afterAll(() => {
    Database.CloseConnections();
  });

  test('Version 2 - property check', async () => {

So even though I'm closing the connections, I'm still getting Jest's open handle error in the end:

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  TLSWRAP

      57 |
      58 |   // Establish connection
    > 59 |   conn.openUri(url, DatabasePrivate.connect_options);
         |        ^
      60 |
      61 |   connections.push(conn);
      62 | }

I'm intentionally using --detectOpenHandles to catch this type of errors. So don't want to remove this flag.

How can I ensure that database connections are closed properly after unit tests completed running?

0 Answers
Related