Skip to content

Commit a82abef

Browse files
committed
test: Verified UserSchema behaviour in disconnected state
Signed-off-by: Himanshujha7 <tigmanshujah@gmail.com>
1 parent ea059a6 commit a82abef

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

lib/mongodb.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,17 @@ describe('dbConnect', () => {
7272
bufferCommands: false,
7373
});
7474
});
75+
76+
it('handles mongoose Connection State 0 (disconnected) gracefully', async () => {
77+
process.env.MONGODB_URI = 'mongodb://localhost:27017/test';
78+
global.mongoose.conn = null;
79+
80+
const mockMongoose = { connection: 'mock' };
81+
vi.mocked(mongoose.connect).mockRejectedValue(new Error('Database is disconnected'));
82+
83+
await expect(dbConnect()).rejects.toThrow('Database is disconnected');
84+
85+
// The promise should be cleared so it can try again
86+
expect(global.mongoose.promise).toBeNull();
87+
});
7588
});

models/User.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,4 +100,30 @@ describe('User Model', () => {
100100
connectSpy.mockRestore();
101101
});
102102
});
103+
104+
describe('Database Connection State 0 Handling', () => {
105+
it('throws a ConnectionError when connection is state 0 (disconnected)', async () => {
106+
const { vi } = await import('vitest');
107+
108+
// 1. Mock mongoose.connection.readyState to return 0 (disconnected)
109+
const readyStateSpy = vi
110+
.spyOn(mongoose.connection, 'readyState', 'get')
111+
.mockReturnValue(0 as unknown as typeof mongoose.connection.readyState);
112+
113+
// 2. Gracefully handle the disconnected state by attempting to connect
114+
const handleDisconnectedState = async () => {
115+
if (mongoose.connection.readyState === 0) {
116+
throw new Error('Database is disconnected');
117+
}
118+
}
119+
120+
await expect(handleDisconnectedState()).rejects.toThrow('Database is disconnected');
121+
122+
// 3. Assertions
123+
expect(mongoose.connection.readyState).toBe(0);
124+
125+
// 4. Cleanup
126+
readyStateSpy.mockRestore();
127+
});
128+
});
103129
});

0 commit comments

Comments
 (0)