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

171
Views
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 answers
Answer question

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 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!