【问题标题】:How To Mock Chained MongoDB Function With Jest如何用 Jest 模拟链式 MongoDB 函数
【发布时间】:2021-08-18 14:50:07
【问题描述】:

我正在尝试模拟 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】:

    试试mockFn.mockReturnThis()

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

    【讨论】:

      猜你喜欢
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 2021-08-11
      相关资源
      最近更新 更多