From 885c40940babe2e446deccfb7e652889c925efe7 Mon Sep 17 00:00:00 2001 From: Mohamed Meabed Date: Mon, 13 Nov 2023 02:01:20 -0500 Subject: [PATCH] chore: fix test port number --- src/__mocks__/mongooseCommon.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/__mocks__/mongooseCommon.ts b/src/__mocks__/mongooseCommon.ts index 90a73576..001843f0 100644 --- a/src/__mocks__/mongooseCommon.ts +++ b/src/__mocks__/mongooseCommon.ts @@ -2,14 +2,29 @@ import mongoose from 'mongoose'; import MongoMemoryServer from 'mongodb-memory-server-core'; +import net, { AddressInfo } from 'net'; const { Schema, Types } = mongoose; mongoose.Promise = Promise; +async function getPortFree() { + return new Promise((res) => { + const srv = net.createServer(); + srv.listen(0, () => { + const port = (srv.address() as AddressInfo).port; + srv.close(() => res(port)); + }); + }); +} + const originalConnect = mongoose.connect; mongoose.createConnection = (async () => { - const mongoServer = await MongoMemoryServer.create(); + const mongoServer = await MongoMemoryServer.create({ + instance: { + port: await getPortFree(), + }, + }); const mongoUri = mongoServer.getUri(); originalConnect.bind(mongoose)(mongoUri, {});