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

172
Vistas
Should I be passing a database instance into my functions or using a testing flag

I'm using Jest, Node 12, and Postgres. I'm a testing noobie and read that establishing a new database object (in my case, with sequelize) is best practice in each test script. So, if I want to test a function in my system, I'd have to pass this new database connection as an argument to the function.

At the moment I'm adding it to the ctx (or context) object which I'm realizing now might have some security holes.

Is it best to pass the database connection as a separate argument in a function, or to initialize the database globally in an export in a "db.js" file or something, then passing a boolean flag in my system functions?

I.e.

function myFunc(5, 'some data', ctx) { ... }
// Where ctx.database is either my live db or test db

or

function myFunc(5, 'some data', databaseInstance, ctx) { ... }
// Where databaseInstance is either my live db or test db

or

function myFunc(5, 'some data', isTest, ctx) { ... }
// If isTest = true then use testDb object

and in db.js

export const liveDb = { ... };
export const testDb = { ... };

In this context, by "best" I mean most secure, and most commonly done.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The most common way would be to use process.NODE_ENV to distinguish between test, dev and prod environments.

So, your db.js can be refactored into something like this:

 const liveDb = { ... };
 const testDb = { ... };

 let db = testDb; // default

if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
  db = testDb
}
if (process.env.NODE_ENV === 'production') {
  db = liveDb
}

export default db;

That way, any importer of db.js will receive the appropriate db object based on the current environment. Jest automatically sets the NODE_ENV variable to 'test'. Also, most nodejs hosting environments will automatically set NODE_ENV to 'production', or you can set it manually in your start script

about 4 years ago · Juan Pablo Isaza 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