Question: What is the proper way of initializing a mongoose connection and gracefully shutting it down at the end of a test set?
Background
As jest runs in parallel I have a routine that sets up a connection with a custom database for each file. The connection and disconnection singleton looks like this:
export const { setup: setupMongoose, disconnect: disconnectMongoose } = (() => {
let connection: Mongoose | null;
let currentURI: string | null = null;
const setup = async ({
URI = config.mongodbSettings.URI,
}: { URI?: string; silent?: boolean } = {}): Promise<Mongoose> => {
if (currentURI && URI && currentURI !== URI) {
throw Error(`Bad URIs - initiated with ${currentURI} but you want to use ${URI}`);
}
if (connection) return connection;
currentURI = URI;
connection = await mongoose.connect(URI, { bufferCommands: false });
return connection;
};
const disconnect = async () => {
if (!connection) return;
await connection.disconnect();
connection = null;
currentURI = null;
};
return { setup, disconnect };
})();
Each script has a short beforeAll and afterAll as below:
export const jestMongooseSetup = (testIdentifier: string) => {
// Connect to Mongoose
beforeAll(async () => {
await setupMongoose({ URI: `mongodb://localhost:27017/test_${testIdentifier}` });
});
// Disconnect all connections and clear
afterAll(async () => {
await disconnectMongoose();
});
};
I've created a super-simple test for illustration:
import { jestMongooseSetup } from 'helpers/jestMongoose';
const testId = 'A';
describe(`${testId}:`, () => {
jestMongooseSetup(testId);
it('2 + 2', () => {
expect(2 + 2).to.equal(4);
});
});
And I've created tests A, B & C and when I run the tests using node --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage src/debug_test/ the output shows a pretty significant increase between each test-file:
PASS src/debug_test/B.spec.ts (117 MB heap size)
PASS src/debug_test/C.spec.ts (157 MB heap size)
PASS src/debug_test/A.spec.ts (188 MB heap size)
Test Suites: 3 passed, 3 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 6.671 s
Ran all test suites matching /src\/debug_test\//i.
Note that this grows by 40MB/per file. This can be reduced to 10MB per file if I initialize the Mongoose in each file but it still feels like way too much for just a connection. I'm aware that there are known memory leaks in Jest (see issues #7874, #6399, #6738, ...) but these issues seem abandoned and 40MB/per file seems too much for an abandoned issue so it would be nice to know what is going on and what the correct way of setting up test jest with mongoose is. I've looked that jest-mongodb but I'm getting tired of new dependency and this should be trivial to solve.