如何用 Jest 模拟链式 MongoDB 函数

How To Mock Chained MongoDB Function With Jest

我正在尝试模拟 MongoClient 的 insertMany 函数。有了这个模拟,我不会使用真正的 mongo db 而不是它,我将使用 Jest 的模拟实现。但是我遇到了

这样的错误

DbConnection.db(...).collection is not a function

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

尝试mockFn.mockReturnThis()

const DbConnection = {
  db: jest.fn().mockReturnThis(),
  collection: jest.fn().mockReturnThis(),
  insertMany: jest.fn().mockResolvedValue({success: true})
}