如何使用 Jest 模拟链式 MongoDB 函数

问题描述 投票:0回答:1

我正在尝试模拟 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
javascript mongodb unit-testing jestjs mocking
1个回答
2
投票

尝试 mockFn.mockReturnThis()

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}
© www.soinside.com 2019 - 2024. All rights reserved.