Search code examples
javascriptmongodbunit-testingjestjsmocking

How To Mock Chained MongoDB Function With Jest


I am trying to mock MongoClient's insertMany functions. With this mock I won't use real mongo db instead of it I will use mock implementation with Jest. However I am having an error like

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

await DbConnection.db().collection(this.collectionName).insertMany(logs);

Mock

const DbConnection = {
  db: () => jest.fn().mockImplementationOnce(() =>({
    collection: () => jest.fn().mockImplementationOnce(() =>({
      insertMany: () => {
        return { success: true }
      },
    })),
  })),
  close: async () => true
};

Error

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

Solution

  • Try mockFn.mockReturnThis()

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

    Then, you can chain call the methods:

    const actual = await DbConnection.db().collection().insertMany();
    // The value of actual is: {success: true}