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

75
Views
Función del módulo de salida de Sinon

Imagina que tengo un archivo aquí:

 // a.js const dbConnection = require('./db-connection.js') module.exports = function (...args) { return async function (req, res, next) { // somethin' somethin' ... const dbClient = dbConnection.db const docs = await dbClient.collection('test').find() if (!docs) { return next(Boom.forbidden()) } } }

, el db-connection.js se ve así:

 const MongoClient = require('mongodb').MongoClient const dbName = 'test' const url = process.env.MONGO_URL const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true, bufferMaxEntries: 0 // dont buffer querys when not connected }) const init = () => { return client.connect().then(() => { logger.info(`mongdb db:${dbName} connected`) const db = client.db(dbName) }) } /** * @type {Connection} */ module.exports = { init, client, get db () { return client.db(dbName) } }

y tengo una prueba para apagar el método find() para devolver al menos verdadero (para probar si el valor de retorno de a.js es verdadero. ¿Cómo puedo hacer eso?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

La estrategia de prueba unitaria es cortar la conexión de la base de datos, no necesitamos conectar el servidor real de la base de datos mongo. Para que podamos ejecutar casos de prueba en un entorno aislado del entorno externo.

Puede usar stub.get(getterFn) reemplaza un nuevo getter para dbConnection.db getter.

Dado que la inicialización del cliente MongoDB ocurre cuando necesita el módulo db-connection . Debe proporcionar una URL correcta para MongoClient desde la variable de entorno antes de solicitar módulos de conexión a y db-connection . De lo contrario, el controlador MongoDB nodejs generará un error de URL no válida.

P.ej

a.js :

 const dbConnection = require('./db-connection.js'); module.exports = function () { const dbClient = dbConnection.db; const docs = dbClient.collection('test').find(); if (!docs) { return true; } };

db-connection.js :

 const MongoClient = require('mongodb').MongoClient; const dbName = 'test'; const url = process.env.MONGO_URL; const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true, }); const init = () => { return client.connect().then(() => { console.info(`mongdb db:${dbName} connected`); const db = client.db(dbName); }); }; module.exports = { init, client, get db() { return client.db(dbName); }, };

a.test.js :

 const sinon = require('sinon'); describe('a', () => { afterEach(() => { sinon.restore(); }); it('should find some docs', () => { process.env.MONGO_URL = 'mongodb://localhost:27017'; const a = require('./a'); const dbConnection = require('./db-connection.js'); const dbStub = { collection: sinon.stub().returnsThis(), find: sinon.stub(), }; sinon.stub(dbConnection, 'db').get(() => dbStub); const actual = a(); sinon.assert.match(actual, true); sinon.assert.calledWithExactly(dbStub.collection, 'test'); sinon.assert.calledOnce(dbStub.find); }); });

Resultado de la prueba:

 a ✓ should find some docs (776ms) 1 passing (779ms) ------------------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ------------------|---------|----------|---------|---------|------------------- All files | 75 | 50 | 25 | 75 | a.js | 100 | 50 | 100 | 100 | 7 db-connection.js | 60 | 100 | 0 | 60 | 11-13,21 ------------------|---------|----------|---------|---------|-------------------
about 4 years ago · Juan Pablo Isaza 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!