我正在尝试模拟 MongoClient 的
insertMany
函数。通过这个模拟,我不会使用真正的 mongo db,而是使用 Jest 的模拟实现。但是我遇到了这样的错误
DbConnection.db(...).collection 不是函数
await DbConnection.db().collection(this.collectionName).insertMany(logs);
const DbConnection = {
db: () => jest.fn().mockImplementationOnce(() =>({
collection: () => jest.fn().mockImplementationOnce(() =>({
insertMany: () => {
return { success: true }
},
})),
})),
close: async () => true
};
DbConnection.db(...).collection is not a function
const DbConnection = {
db: jest.fn().mockReturnThis(),
collection: jest.fn().mockReturnThis(),
insertMany: jest.fn().mockResolvedValue({success: true})
}
然后,您可以链式调用这些方法:
const actual = await DbConnection.db().collection().insertMany();
// The value of actual is: {success: true}