diff --git a/lib/mongodb.test.ts b/lib/mongodb.test.ts index 778213af..1440667a 100644 --- a/lib/mongodb.test.ts +++ b/lib/mongodb.test.ts @@ -113,6 +113,34 @@ describe('dbConnect', () => { expect(global.mongoose.promise).toBeNull(); }); + it('handles mongoose Connection State 3 (disconnecting) gracefully', async () => { + process.env.MONGODB_URI = 'mongodb://localhost:27017/test'; + global.mongoose.conn = null; + mockMongooseConnection.readyState = 3; + + const mockMongoose = { connection: 'mock' }; + setConnectedMongoose(mockMongoose as unknown as typeof mongoose); + + const conn = await dbConnect(); + + expect(mongoose.connect).toHaveBeenCalledTimes(1); + expect(conn).toBe(mockMongoose); + expect(global.mongoose.conn).toBe(mockMongoose); + }); + + it('returns the cached connection immediately when mongoose is already connected', async () => { + process.env.MONGODB_URI = 'mongodb://localhost:27017/test'; + + const mockMongoose = { connection: 'mock' }; + global.mongoose.conn = mockMongoose as unknown as typeof mongoose; + mockMongooseConnection.readyState = 1; + + const conn = await dbConnect(); + + expect(conn).toBe(mockMongoose); + expect(mongoose.connect).not.toHaveBeenCalled(); + }); + it('throws when called from the Edge runtime', async () => { vi.stubEnv('NEXT_RUNTIME', 'edge'); process.env.MONGODB_URI = 'mongodb://localhost:27017/test'; diff --git a/models/User.test.ts b/models/User.test.ts index dcdc03fb..32ecd985 100644 --- a/models/User.test.ts +++ b/models/User.test.ts @@ -270,6 +270,20 @@ describe('User Model', () => { connectSpy.mockRestore(); }); }); + + describe('Database Connection State 1 Handling', () => { + it('keeps the User model usable while mongoose is connected', async (): Promise => { + const readyStateSpy = vi + .spyOn(mongoose.connection, 'readyState', 'get') + .mockReturnValue(1 as unknown as typeof mongoose.connection.readyState); + + expect(mongoose.connection.readyState).toBe(1); + expect(User).toBeDefined(); + expect(User.modelName).toBe('User'); + + readyStateSpy.mockRestore(); + }); + }); }); /* ==========================================================================