Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda