Jest not closing because of Mongoose.model
Using a setup file and setupFilesAfterEnv
Jest can call a "setup.js" file to run some beforeAll
and afterAll
functions. As ongoing Mongoose's connections keep Jest open, we will close them using the afterAll
hook.
Solution
- In your
jest.config.js
, add the following lines:
setupFilesAfterEnv: [ '<rootDir>/tests/setup.js', // <- Feel free to place this file wherever it's convinient],
- Create a
setup.js
file with the following code:
import { getMongoDBInstance } from '../src/bin/server.ts';afterAll(async () => { const mongoDB = getMongoDBInstance(); await mongoDB.connection.close();});
Here, getMongoDBInstance
is a function that returns me the instance of Mongoose I instantiate when my server boots.
let mongoDB;async function initServer() { ... await mongoose.connect(uristring, { useNewUrlParser: true, useUnifiedTopology: true, }); mongoDB = mongoose; ...}export const getMongoDBInstance = () => mongoDB;
And now after all tests ran, Jest will call this function and close any MongoDB connections! You can follow the same to solve open connections with knex, or any other node ORMs.
Try changing await mongoose.connection.close()
to await mongoose.disconnect();
. Worked for me.