How to Mock the mongodb NPM Library with Jest (Complete Guide for Developers)

As a senior developer, one of the first things I ensure in any Node.js backend is proper unit testing—and mocking external libraries like mongodb is key to making those tests fast and isolated.

In this article, you’ll learn how to mock the mongodb npm package using Jest. Whether you're using the native driver directly or connecting through a helper, this guide covers the basics and includes examples.


🔍 Why Mock mongodb in Jest?

The mongodb library establishes a real connection to a database, which is unnecessary (and slow) during unit tests. By mocking it, you:

  • Eliminate external dependencies
  • Speed up test runs
  • Control test behavior with predictable mock responses
  • Avoid writing/reading from a real MongoDB instance

⚙️ Prerequisites

Make sure your project includes:

npm install mongodb
npm install --save-dev jest

If you're using TypeScript:

npm install --save-dev @types/jest ts-jest

🧪 Let’s Say You Have This Code

db.js

const { MongoClient } = require('mongodb');

const uri = process.env.MONGO_URI;
const client = new MongoClient(uri);
let db;

async function connectToDatabase() {
  if (!db) {
    await client.connect();
    db = client.db('mydatabase');
  }
  return db;
}

module.exports = { connectToDatabase };

✅ How to Mock mongodb with Jest

Step 1: Create a Mock

You can use Jest’s built-in mocking to replace the mongodb package.

✅ Basic Example

__mocks__/mongodb.js

const mConnect = jest.fn();
const mDb = {
  collection: jest.fn().mockReturnThis(),
  findOne: jest.fn(),
};

const mClient = {
  connect: mConnect,
  db: jest.fn(() => mDb),
};

const MongoClient = jest.fn(() => mClient);

module.exports = {
  MongoClient,
};

Step 2: Tell Jest to Use the Mock

In your test file:

db.test.js

jest.mock('mongodb'); // <-- this uses the mock file in __mocks__

const { connectToDatabase } = require('./db');
const { MongoClient } = require('mongodb');

describe('connectToDatabase', () => {
  it('should return the mocked database instance', async () => {
    const db = await connectToDatabase();
    expect(db.collection).toBeDefined();
    expect(MongoClient).toHaveBeenCalledTimes(1);
  });
});

🧪 Bonus: Mocking Collection Methods

To go deeper, you can mock collection methods like insertOne, find, etc.

Update __mocks__/mongodb.js

const mCollection = {
  findOne: jest.fn().mockResolvedValue({ name: 'Test User' }),
  insertOne: jest.fn().mockResolvedValue({ acknowledged: true, insertedId: '123' }),
};

const mDb = {
  collection: jest.fn(() => mCollection),
};

const mClient = {
  connect: jest.fn(),
  db: jest.fn(() => mDb),
};

const MongoClient = jest.fn(() => mClient);

module.exports = {
  MongoClient,
};

Now you can assert on insertOne, findOne, etc., just like real methods—but with full control.


🛠 Pro Tip: Reset Mocks Between Tests

Add this in your test file:

beforeEach(() => {
  jest.clearAllMocks();
});

✅ Final Thoughts

Mocking the mongodb npm library in Jest is straightforward once you understand the MongoDB client structure. By mocking MongoClient, connect(), and db().collection(), you can write fast, reliable, and isolated unit tests—just like a pro.