Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

742
Vistas
Jest mock nested functions of MongoDB

I have a helper class that manages the MongoDB client methods.

class Common {
   constructor() {
        this._client = null;
   }
   
   static async connect(url) {
        this._client = await MongoClient.connect(url, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        return this._client;
    }

    static async getCollection({ url, db_name, collection_name }) {
        const client = await Common.connect(url);

        return client.db(db_name).collection(collection_name);
    }
   
}

I am trying to write the test case for the getCollection method. This is what I tried

jest.mock('mongodb');
it('To check if the collection method on the MongoClient instance was invoked', () => {
    Common.getCollection({});

    const mockMongoClientInstance = MongoClient.mock.instances[0];
    const mockMongoDBConnect = mockMongoClientInstance.connect;
    expect(mockMongoDBConnect).toHaveBeenCalledTimes(1);
});

Obviously, this test case covers the first line of the getCollection method and the test case actually tries to execute the second line. How can I mock the second line? Any suggestion would be helpful. Thanks in advance.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can use jest.spyOn(object, methodName) to mock Common.connect() and MongoClient.connect() methods.

E.g.

common.js:

import { MongoClient } from 'mongodb';

export class Common {
  constructor() {
    this._client = null;
  }

  static async connect(url) {
    this._client = await MongoClient.connect(url, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    return this._client;
  }

  static async getCollection({ url, db_name, collection_name }) {
    const client = await Common.connect(url);

    return client.db(db_name).collection(collection_name);
  }
}

common.test.js:

import { Common } from './common';
import { MongoClient } from 'mongodb';

describe('66848944', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  describe('#getCollection', () => {
    it('To check if the collection method on the MongoClient instance was invoked', async () => {
      const client = { db: jest.fn().mockReturnThis(), collection: jest.fn() };
      const connectSpy = jest.spyOn(Common, 'connect').mockResolvedValueOnce(client);
      await Common.getCollection({ url: 'mongodb://localhost:27017', db_name: 'awesome', collection_name: 'products' });
      expect(connectSpy).toBeCalledWith('mongodb://localhost:27017');
      expect(client.db).toBeCalledWith('awesome');
      expect(client.collection).toBeCalledWith('products');
    });
  });

  describe('#connect', () => {
    it('should connect to mongo db', async () => {
      const connectSpy = jest.spyOn(MongoClient, 'connect').mockReturnValueOnce({});
      const actual = await Common.connect('mongodb://localhost:27017');
      expect(actual).toEqual({});
      expect(connectSpy).toBeCalledWith('mongodb://localhost:27017', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      });
    });
  });
});

unit test result:

 PASS  examples/66848944/common.test.js
  66848944
    #getCollection
      ✓ To check if the collection method on the MongoClient instance was invoked (5 ms)
    #connect
      ✓ should connect to mongo db (1 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   85.71 |      100 |   66.67 |   85.71 |                   
 common.js |   85.71 |      100 |   66.67 |   85.71 | 5                 
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.165 s, estimated 6 s
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda