Berkin
Berkin

Reputation: 1664

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

Upvotes: 0

Views: 841

Answers (1)

Lin Du
Lin Du

Reputation: 102237

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}

Upvotes: 2

Related Questions