From 56d9f4740a9fd59b60c7721f5e150d07c11aa209 Mon Sep 17 00:00:00 2001 From: bhoomisingh00079 Date: Mon, 1 Jun 2026 08:46:55 +0530 Subject: [PATCH] test(mongodb): add coverage for disconnected, connected, and connecting states --- lib/mongodb.test.ts | 28 ++++++++++++++++++++++++++++ models/User.test.ts | 14 ++++++++++++++ 2 files changed, 42 insertions(+) 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 247b8920..7d440dfa 100644 --- a/models/User.test.ts +++ b/models/User.test.ts @@ -266,6 +266,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(); + }); + }); }); /* ==========================================================================