【发布时间】:2021-09-01 20:17:56
【问题描述】:
如何返回一个 mongodb.connection.db() 类型值并模拟它的集合? 我创建了一个 mongoClient 类型的连接并使用它的 db() 函数。如果一切正常,我输入了这个的集合信息,但我不能写测试,因为我不能模拟它。
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();
【问题讨论】:
标签: typescript unit-testing jestjs mocking ts-jest