Muthu Palanisamy
Muthu Palanisamy

Reputation: 775

Closing a MongoDB connection after running Mocha tests for an Express application

I have an Express application that looks like this.

const app = express();

...
...
...

router.post(...);
router.get(...);
router.delete(...);

app.use('/api/v1', router);

MongoClient.connect(mongoUri, { useNewUrlParser: true })
    .then(client => {
        const db = client.db('db_name');
        const collection = db.collection('collection_name');
        app.locals.collection = collection;
    })
    .catch(error => console.error(error));

const server = app.listen(settings.APIServerPort, () => console.log(`Server is listening on port ${settings.APIServerPort}.`));

module.exports = {

    server,
    knex // using this to connect to the RDBMS
}

The application uses both an RDBMS and Mongo.

I wrote tests for the application using Mocha and added the following block to the Mocha test.

const app = require('../app');

...test 1...
...test 2...
...test 3...
...
...
...
...test n...

after(async () => {

    await app.knex.destroy();
});

The after hook closes out my connection to the RDBMS.

However, I don't know how to close the MongoDB connection once the test finishes.

Owing to keeping this connection open, the test never exits and hangs once all the tests have been run.

The closest answer that I have been able to find is this one - Keep MongoDB connection open while running tests using mocha framework.

However, I was unable to get to work for me.

Can someone please help with this?

Update A combination of the answers below is what solved the problem.

const mongoClient = new MongoClient(mongoUri, { useNewUrlParser: true });

mongoClient.connect()
    .then(client => {
        const db = client.db('...');
        const collection = db.collection('...');
        app.locals.collection = collection;
    })
    .catch(error => console.error(error));

const server = app.listen(settings.APIServerPort, () => console.log(`Server is listening on port ${settings.APIServerPort}.`));

module.exports = {

    server,
    knex, 
    mongoClient
}

Upvotes: 2

Views: 684

Answers (1)

Siddharth Jadhav
Siddharth Jadhav

Reputation: 71

We can rewrite the mongo function to make it work

const client = new MongoClient(uri);

client.connect()
    .then(client => {
        const db = client.db('db_name');
        const collection = db.collection('collection_name');
        app.locals.collection = collection;
    })
    .catch(error => console.error(error));

And in the after block -

after(async () => {

    await app.knex.destroy();
    await client.close();

});

Upvotes: 2

Related Questions