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