1+ import { describe , expect , it , jest , beforeEach , afterEach } from '@jest/globals' ;
2+ import mongoose from 'mongoose' ;
3+ import { connectDB } from '../../index' ;
4+
5+ // Mock mongoose
6+ jest . mock ( 'mongoose' ) ;
7+ const mockedMongoose = mongoose as jest . Mocked < typeof mongoose > ;
8+
9+ // Mock console methods
10+ const consoleLogSpy = jest . spyOn ( console , 'log' ) . mockImplementation ( ( ) => { } ) ;
11+ const consoleErrorSpy = jest . spyOn ( console , 'error' ) . mockImplementation ( ( ) => { } ) ;
12+ const processExitSpy = jest . spyOn ( process , 'exit' ) . mockImplementation ( ( ) => {
13+ throw new Error ( 'process.exit called' ) ;
14+ } ) ;
15+
16+ describe ( 'Database Connection' , ( ) => {
17+ beforeEach ( ( ) => {
18+ jest . clearAllMocks ( ) ;
19+ process . env . MONGO_URI = 'mongodb+srv://test:test@test.mongodb.net/test?retryWrites=false&ssl=true' ;
20+ } ) ;
21+
22+ afterEach ( ( ) => {
23+ consoleLogSpy . mockClear ( ) ;
24+ consoleErrorSpy . mockClear ( ) ;
25+ processExitSpy . mockClear ( ) ;
26+ } ) ;
27+
28+ it ( 'should connect to MongoDB successfully' , async ( ) => {
29+ mockedMongoose . connect . mockResolvedValueOnce ( mongoose ) ;
30+
31+ await connectDB ( ) ;
32+
33+ expect ( mockedMongoose . connect ) . toHaveBeenCalledTimes ( 1 ) ;
34+ expect ( mockedMongoose . connect ) . toHaveBeenCalledWith (
35+ process . env . MONGO_URI ,
36+ {
37+ retryWrites : false ,
38+ ssl : true
39+ }
40+ ) ;
41+ expect ( consoleLogSpy ) . toHaveBeenCalledWith ( 'Connected to Azure Cosmos DB (MongoDB API)' ) ;
42+ } ) ;
43+
44+ it ( 'should handle connection failure and exit process' , async ( ) => {
45+ const mockError = new Error ( 'Connection failed' ) ;
46+ mockedMongoose . connect . mockRejectedValueOnce ( mockError ) ;
47+
48+ await expect ( connectDB ( ) ) . rejects . toThrow ( 'process.exit called' ) ;
49+
50+ expect ( mockedMongoose . connect ) . toHaveBeenCalledTimes ( 1 ) ;
51+ expect ( consoleErrorSpy ) . toHaveBeenCalledWith ( 'MongoDB connection failed:' , mockError ) ;
52+ expect ( processExitSpy ) . toHaveBeenCalledWith ( 1 ) ;
53+ } ) ;
54+
55+ it ( 'should use environment variable for connection string' , async ( ) => {
56+ const testUri = 'mongodb+srv://custom:uri@test.mongodb.net/custom?retryWrites=false&ssl=true' ;
57+ process . env . MONGO_URI = testUri ;
58+ mockedMongoose . connect . mockResolvedValueOnce ( mongoose ) ;
59+
60+ await connectDB ( ) ;
61+
62+ expect ( mockedMongoose . connect ) . toHaveBeenCalledWith ( testUri , {
63+ retryWrites : false ,
64+ ssl : true
65+ } ) ;
66+ } ) ;
67+ } ) ;
0 commit comments