'MongoDB connetion will not close in Jest afterAll()

Here's the current state of my setup and tear down methods:

beforeAll(async () => {
    // await populate();

    try {
        await client.connect(() => console.log("Connection opened"));

        const db = client.db('trallo');
        const cards = db.collection('cards');

        const hello = {
            title: "Hello",
            description: "Goodbye"
        };

        const card = await cards.insertOne(hello);

        const todo = {
            title: "Todo",
            cards: [card.insertedId]
        }

        const inProgress = {
            title: "In progress",
            cards: []
        }

        const done = {
            title: "Done",
            cards: []
        }

        const lists = db.collection('lists');
        const list = await lists.insertMany([todo, inProgress, done]);

        const dummy = {
            title: "Dummy",
            lists: Object.keys(list.insertedIds).map(key => list.insertedIds[key])
        }

        const boards = db.collection('boards');
        const board = await boards.insertOne(dummy);



    } finally {
        // Ensures that the client will close when you finish/error
        await client.close(() => console.log("Connection closed"));
        // done();
    }
});

afterAll(async () => {
    // await deleteAll();

    try {
        await client.connect(() => console.log("Connection opened"));
        const db = client.db('trallo');
        const cards = db.collection('cards');
        await cards.deleteMany({});

        const lists = db.collection('lists');
        await lists.deleteMany({});

        const boards = db.collection('boards');
        await boards.deleteMany({});

    } finally {
        // Ensures that the client will close when you finish/error
        await client.close(() => console.log("Connection closed"));
        // done();
    }
});

I've tried increasing timeout time, moved around where connections are opened and closed, passed a 'done' callback in both tests and setup/teardown, nothing has worked so far.

Here's what I get when jest is run:

 RUNS  functional-tests/homepage.test.js

Test Suites: 1 failed, 1 total Tests: 1 failed, 1 total Snapshots: 0 total Time: 1.218 s, estimated 6 s Ran all test suites matching /functional-tests/i.

Jest has detected the following 2 open handles potentially keeping Jest from exiting:

● TCPWRAP

  12 |
  13 |         try {
> 14 |             await client.connect(() => console.log("Connection opened"));
     |                          ^
  15 |
  16 |             const db = client.db('trallo');
  17 |             const cards = db.collection('cards');

  at resolveSRVRecord (../node_modules/mongodb/src/connection_string.ts:81:7)
  at connect (../node_modules/mongodb/src/operations/connect.ts:42:28)
  at ../node_modules/mongodb/src/mongo_client.ts:425:14
  at maybePromise (../node_modules/mongodb/src/utils.ts:517:3)
  at MongoClient.connect (../node_modules/mongodb/src/mongo_client.ts:424:24)
  at Object.connect (homepage.test.js:14:26)
  at TestScheduler.scheduleTests (../node_modules/@jest/core/build/TestScheduler.js:317:13)
  at runJest (../node_modules/@jest/core/build/runJest.js:407:19)
  at _run10000 (../node_modules/@jest/core/build/cli/index.js:338:7)
  at runCLI (../node_modules/@jest/core/build/cli/index.js:190:3)

● TCPWRAP

  63 |
  64 |         try {
> 65 |             await client.connect(() => console.log("Connection opened"));
     |                          ^
  66 |             const db = client.db('trallo');
  67 |             const cards = db.collection('cards');
  68 |             await cards.deleteMany({});

  at resolveSRVRecord (../node_modules/mongodb/src/connection_string.ts:81:7)
  at connect (../node_modules/mongodb/src/operations/connect.ts:42:28)
  at ../node_modules/mongodb/src/mongo_client.ts:425:14
  at maybePromise (../node_modules/mongodb/src/utils.ts:517:3)
  at MongoClient.connect (../node_modules/mongodb/src/mongo_client.ts:424:24)
  at Object.connect (homepage.test.js:65:26)
  at TestScheduler.scheduleTests (../node_modules/@jest/core/build/TestScheduler.js:317:13)
  at runJest (../node_modules/@jest/core/build/runJest.js:407:19)
  at _run10000 (../node_modules/@jest/core/build/cli/index.js:338:7)
  at runCLI (../node_modules/@jest/core/build/cli/index.js:190:3)

● Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "Connection opened".

  63 |
  64 |         try {
> 65 |             await client.connect(() => console.log("Connection opened"));
     |                                                ^
  66 |             const db = client.db('trallo');
  67 |             const cards = db.collection('cards');
  68 |             await cards.deleteMany({});

  at console.log (../node_modules/@jest/console/build/CustomConsole.js:172:10)
  at log (homepage.test.js:65:48)
  at ../node_modules/mongodb/src/utils.ts:532:5
  at ../node_modules/mongodb/src/mongo_client.ts:427:9
  at connectCallback (../node_modules/mongodb/src/operations/connect.ts:38:5)
  at ../node_modules/mongodb/src/operations/connect.ts:103:5
  at ../node_modules/mongodb/src/sdam/topology.ts:476:47
  at ../node_modules/mongodb/src/cmap/connection_pool.ts:482:13
  at handleOperationResult (../node_modules/mongodb/src/sdam/server.ts:538:14)
  at Connection.onMessage (../node_modules/mongodb/src/cmap/connection.ts:452:5)

● Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "Connection opened".

  12 |
  13 |         try {
> 14 |             await client.connect(() => console.log("Connection opened"));
     |                                                ^
  15 |
  16 |             const db = client.db('trallo');
  17 |             const cards = db.collection('cards');

  16 |             const db = client.db('trallo');
  17 |             const cards = db.collection('cards');

  at console.log (../node_modules/@jest/console/build/CustomConsole.js:172:10)
  17 |             const cards = db.collection('cards');

  at console.log (../node_modules/@jest/console/build/CustomConsole.js:172:10)
  at log (homepage.test.js:14:48)
  at ../node_modules/mongodb/src/utils.ts:532:5
  at ../node_modules/mongodb/src/mongo_client.ts:427:9
  at connectCallback (../node_modules/mongodb/src/operations/connect.ts:38:5)
  at ../node_modules/mongodb/src/operations/connect.ts:103:5
  at ../node_modules/mongodb/src/sdam/topology.ts:476:47
  at ../node_modules/mongodb/src/cmap/connection_pool.ts:482:13
  at handleOperationResult (../node_modules/mongodb/src/sdam/server.ts:538:14)
  at Connection.onMessage (../node_modules/mongodb/src/cmap/connection.ts:452:5)

Terminate batch job (Y/N)? y PS C:\Users\tracii\Documents\Projects\trallo> cd .\server\db
PS C:\Users\tracii\Documents\Projects\trallo\server\db> node .\mongoSeed.js Connection closed Connection closed PS C:\Users\tracii\Documents\Projects\trallo\server\db>



Solution 1:[1]

Try writing the test the same as how they do in the Jest docs when connecting to the DB, may help: https://jestjs.io/docs/mongodb

So instead of (Where I'm assuming client is a new instance of MongoClient):

beforeAll(async () => {    
    try {
        await client.connect(() => console.log("Connection opened"));

        const db = client.db('trallo');
        // ...rest of the code

Try awaiting the MongoClient and immediately connecting like so:

describe('Your test', () => {
let connection;
let db;

beforeAll(async () => {
    try {
        connection = await MongoClient.connect("YOUR_MONGO_URI");
        db = await connection.db("trallo");
        // ...rest of the code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tracy Nguyen