import { mongodbClient } from "../mongodb-client"; import { MongoClient } from "mongodb"; describe("MongoDBClient Validation", () => { const originalEnv = process.env; beforeEach(() => { process.env = { ...originalEnv }; delete process.env.MONGO_URI; delete process.env.MONGODB_URI; delete process.env.MONGODB_DB_NAME; // Force reset singleton state (mongodbClient as any).client = null; (mongodbClient as any).db = null; }); afterAll(async () => { process.env = originalEnv; // Ensure we are disconnected await mongodbClient.disconnect(); }); it("should throw error if no URI is provided", async () => { await expect(mongodbClient.connect()).rejects.toThrow( "[core-db] Configuration Error: 'MONGO_URI' is missing", ); }); it("should throw error if an invalid URI format is provided", async () => { await expect(mongodbClient.connect("not-a-mongo-uri")).rejects.toThrow( "[core-db] Connection Error: The provided MongoDB URI is invalid", ); }); it("should throw error if URI is valid but database name is missing", async () => { // We mock the actual MongoClient connection so it doesn't try to hit a real network const connectSpy = jest .spyOn(MongoClient.prototype, "connect") .mockResolvedValue({} as any); const uriWithoutDb = "mongodb://127.0.0.1:27017"; await expect(mongodbClient.connect(uriWithoutDb)).rejects.toThrow( "[core-db] Database name not specified", ); connectSpy.mockRestore(); }); it("should succeed when valid URI and DB name are provided", async () => { const mockDb = { databaseName: "my-db" }; const connectSpy = jest .spyOn(MongoClient.prototype, "connect") .mockResolvedValue({} as any); const dbSpy = jest .spyOn(MongoClient.prototype, "db") .mockReturnValue(mockDb as any); const validUri = "mongodb://127.0.0.1:27017/my-db"; await mongodbClient.connect(validUri); expect(mongodbClient.getDb()).toBeDefined(); expect(mongodbClient.getDb().databaseName).toBe("my-db"); connectSpy.mockRestore(); dbSpy.mockRestore(); }); });