Search code examples
node.jstypescriptunit-testingjestjsts-jest

How To Mock MongoDB ( mongoClient ) With Jest


I have a DBManager class to connect to mongoClient

import { MongoClient } from 'mongodb';

class DBManager {
  private url = process.env.MONGODB_URL;

  private _connection: MongoClient;

  constructor() {
    this._connection = null;
  }
  get connection() {
    return this._connection;
  }

  async start() {
    if (!this._connection) {
      this._connection = await MongoClient.connect(this.url);
    }
  }
}

export default new DBManager();

and I call this class like this

await DBManager.start();
const db = DBManager.connection.db(); 

I get this error when I try to mock:

Received: [TypeError: db_manager_1.default.connection.db is not a function]

this is how to mock method i use:

  DBManager.start = jest.fn().mockResolvedValue(() => ({
      connection: jest.fn().mockReturnThis(),
      db: jest.fn().mockResolvedValue({success: true})
    }));

thanks..


Solution

  • You can use a real MongoDB server to use in tests with the package mongodb-memory-server.

    So in your case, you just need to do:

    import { MongoMemoryServer } from '../index';
    
    describe('Single MongoMemoryServer', () => {
      let con;
      let mongoServer;
    
      beforeAll(async () => {
        mongoServer = await MongoMemoryServer.create();
        process.env.MONGODB_URL = mongoServer.getUri();
      });
    
      afterAll(async () => {
        if (con) {
          await con.close();
        }
        if (mongoServer) {
          await mongoServer.stop();
        }
      });
    
      it('DBManager connection', async () => {
        await DBManager.start();
        const db = DBManager.connection.db();
        // ...
    });