Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

741
Views
Jest se burla de las funciones anidadas de MongoDB

Tengo una clase auxiliar que administra los métodos de cliente de MongoDB.

 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); } }

Estoy tratando de escribir el caso de prueba para el método getCollection. Esto es lo que probé

 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); });

Obviamente, este caso de prueba cubre la primera línea del método getCollection y el caso de prueba en realidad intenta ejecutar la segunda línea. ¿Cómo puedo burlarme de la segunda línea? Cualquier sugerencia sería muy útil. Gracias por adelantado.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Puede usar jest.spyOn(object, methodName) para burlarse de Common.connect() y MongoClient.connect() .

P.ej

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, }); }); }); });

resultado de la prueba unitaria:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!