Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions lib/mongodb.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
14 changes: 14 additions & 0 deletions models/User.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> => {
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();
});
});
});

/* ==========================================================================
Expand Down
Loading