Skip to content

Commit 56d9f47

Browse files
test(mongodb): add coverage for disconnected, connected, and connecting states
1 parent e6b5723 commit 56d9f47

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

lib/mongodb.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,34 @@ describe('dbConnect', () => {
113113
expect(global.mongoose.promise).toBeNull();
114114
});
115115

116+
it('handles mongoose Connection State 3 (disconnecting) gracefully', async () => {
117+
process.env.MONGODB_URI = 'mongodb://localhost:27017/test';
118+
global.mongoose.conn = null;
119+
mockMongooseConnection.readyState = 3;
120+
121+
const mockMongoose = { connection: 'mock' };
122+
setConnectedMongoose(mockMongoose as unknown as typeof mongoose);
123+
124+
const conn = await dbConnect();
125+
126+
expect(mongoose.connect).toHaveBeenCalledTimes(1);
127+
expect(conn).toBe(mockMongoose);
128+
expect(global.mongoose.conn).toBe(mockMongoose);
129+
});
130+
131+
it('returns the cached connection immediately when mongoose is already connected', async () => {
132+
process.env.MONGODB_URI = 'mongodb://localhost:27017/test';
133+
134+
const mockMongoose = { connection: 'mock' };
135+
global.mongoose.conn = mockMongoose as unknown as typeof mongoose;
136+
mockMongooseConnection.readyState = 1;
137+
138+
const conn = await dbConnect();
139+
140+
expect(conn).toBe(mockMongoose);
141+
expect(mongoose.connect).not.toHaveBeenCalled();
142+
});
143+
116144
it('throws when called from the Edge runtime', async () => {
117145
vi.stubEnv('NEXT_RUNTIME', 'edge');
118146
process.env.MONGODB_URI = 'mongodb://localhost:27017/test';

models/User.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,20 @@ describe('User Model', () => {
266266
connectSpy.mockRestore();
267267
});
268268
});
269+
270+
describe('Database Connection State 1 Handling', () => {
271+
it('keeps the User model usable while mongoose is connected', async (): Promise<void> => {
272+
const readyStateSpy = vi
273+
.spyOn(mongoose.connection, 'readyState', 'get')
274+
.mockReturnValue(1 as unknown as typeof mongoose.connection.readyState);
275+
276+
expect(mongoose.connection.readyState).toBe(1);
277+
expect(User).toBeDefined();
278+
expect(User.modelName).toBe('User');
279+
280+
readyStateSpy.mockRestore();
281+
});
282+
});
269283
});
270284

271285
/* ==========================================================================

0 commit comments

Comments
 (0)