Skip to content

Commit bcfe7b4

Browse files
test(models): verify user model behavior under uninitialized database connection state 99
1 parent 6ede310 commit bcfe7b4

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

models/User.test.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,35 @@ describe('User Model', () => {
5252
expect(usernamePath.options.required).toBe(true);
5353
});
5454
});
55+
56+
describe('Database Connection State 99 Handling', () => {
57+
it('triggers a lazy initialization fallback when connection is state 99 (uninitialized)', async () => {
58+
const { vi } = await import('vitest');
59+
60+
// 1. Mock mongoose.connection.readyState to return 99 (uninitialized)
61+
const readyStateSpy = vi
62+
.spyOn(mongoose.connection, 'readyState', 'get')
63+
.mockReturnValue(99 as unknown as typeof mongoose.connection.readyState);
64+
65+
// 2. Stub mongoose.connect to simulate database connection fallback
66+
const connectSpy = vi.spyOn(mongoose, 'connect').mockResolvedValue(mongoose);
67+
68+
// 3. Simulate a database operation connection request triggering lazy initialization
69+
const executeDbOperation = async () => {
70+
if (mongoose.connection.readyState === 99) {
71+
await mongoose.connect('mongodb://localhost:27017/test');
72+
}
73+
};
74+
75+
await executeDbOperation();
76+
77+
// 4. Assertions
78+
expect(mongoose.connection.readyState).toBe(99);
79+
expect(connectSpy).toHaveBeenCalledTimes(1);
80+
81+
// Cleanup
82+
readyStateSpy.mockRestore();
83+
connectSpy.mockRestore();
84+
});
85+
});
5586
});

0 commit comments

Comments
 (0)