Is there a way to return a mongodb.connection.db() type value and mock its collection for testing purposes? I have implemented a mongoClient connection and use its db() function. If everything is set up correctly, I should be able to access the collections but I am finding it difficult to write tests due to the inability to mock it.
dbManager.ts
import { MongoClient } from 'mongodb';
class DBManager {
private connection?: MongoClient;
private mongoUrl = null;
constructor(url: string) {
this.mongoUrl = url;
}
get db() {
return this.connection!.db();
}
async start() {
if (!this.connection) {
this.connection = await MongoClient.connect(this.mongoUrl);
}
}
}
export default DBManager;
index.ts
const dbManager = new DBManager(url);
await dbManager.start();
const db = dbManager.db;
if (db) {
const collection = db.collection(collectionName);
}
index.spec.ts
const dbManager = new DBManager( 'mongoUrl');
jest.spyOn(dbManager, 'start').mockResolvedValue();
jest.spyOn(dbManager, 'db', 'get').mockImplementation();