@@ -3,6 +3,13 @@ import { MongoMemoryServer } from "mongodb-memory-server";
33
44let mongod : MongoMemoryServer | null = null ;
55
6+ jest . setTimeout ( 30000 ) ;
7+
8+ function getMongoPort ( basePort : number ) {
9+ const workerId = Number ( process . env . JEST_WORKER_ID || "0" ) ;
10+ return basePort + workerId ;
11+ }
12+
613// Suppress console.error during tests to reduce noise
714const originalError = console . error ;
815beforeAll ( ( ) => {
@@ -17,14 +24,13 @@ afterAll(() => {
1724// @shelf /jest-mongodb provides global.__MONGO_URI__ through globalSetup
1825// If not available, set up MongoDB Memory Server manually
1926beforeAll ( async ( ) => {
20- let mongoUri = ( global as any ) . __MONGO_URI__ || process . env . MONGO_URL ;
21-
22- // If @shelf /jest-mongodb didn't set up MongoDB, do it manually
23- if ( ! mongoUri ) {
24- mongod = await MongoMemoryServer . create ( ) ;
25- mongoUri = mongod . getUri ( ) ;
26- ( global as any ) . __MONGO_URI__ = mongoUri ;
27- }
27+ mongod = await MongoMemoryServer . create ( {
28+ instance : {
29+ ip : "127.0.0.1" ,
30+ port : getMongoPort ( 38017 ) ,
31+ } ,
32+ } ) ;
33+ const mongoUri = mongod . getUri ( ) ;
2834
2935 if ( mongoose . connection . readyState === 0 ) {
3036 await mongoose . connect ( mongoUri ) ;
@@ -33,13 +39,16 @@ beforeAll(async () => {
3339
3440afterAll ( async ( ) => {
3541 if ( mongoose . connection . readyState !== 0 ) {
36- await mongoose . connection . close ( ) ;
42+ await mongoose . disconnect ( ) ;
3743 }
3844
3945 // Clean up manually created MongoDB instance if it exists
4046 if ( mongod ) {
41- await mongod . stop ( ) ;
47+ await mongod . stop ( { doCleanup : true , force : true } ) ;
48+ mongod = null ;
4249 }
50+
51+ delete ( global as any ) . __MONGO_URI__ ;
4352} ) ;
4453
4554// Clean up database after each test
0 commit comments