I am using Mongoose to connect to MongoDB. While testing my code with Jest, the tests passed but never terminated.
In my mongoDB.service.ts
I have:
private connections: Map<number, Connection> = new Map();
private connection: Connection;
Because I want to connect multiple dbs.
I use the connection
to set the db connection and add it to the connections
map
this.connection.useDb(dbName);
I implemented OnApplicationShutdown:
async onApplicationShutdown(): Promise<void> {
for (const [orgId, connection] of this.connections) {
await connection
.close()
.then(() => {
console.log(`Connection for organization ID ${orgId} closed.`);
})
.catch((e) => {
console.error(`Failed to close connection for organization ID ${orgId}: ${e}`);
});
}
this.connections.clear();
await this.connection
.close()
.then(() => {
console.log("Secondary MongoDB connection closed.");
})
.catch((e) => {
console.error(`Failed to close secondary MongoDB connection: ${e}`);
});
await mongoose.connection
.close()
.then(() => {
console.log("Primary MongoDB connection closed.");
})
.catch((e) => {
console.error(`Failed to close primary MongoDB connection: ${e}`);
});
}
In my tests I have afterAll()
:
afterAll(async () => {
await module.close();
}, 60000);
I debugged it, and it seems that the connections are closed. However, the tests never terminated.
I know it has been asked before MongoDB connections do not close in test scenarios, but never answered.
How to solve it?