Wait for DB initialization before running Jest tests

Viewed 1402

I have to add some features, and their corresponding tests, to an API backend I developed some months ago using NodeJS. Checking the test cases I wrote back then, I've come across with this code:

index-route.spec.js

const app = require('../../app');

const request = require('supertest');

function delay() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, 3000);
  });
}

beforeAll(async () => {
  await delay();
});

// START TESTS

The reason of this delay is to give time to the application to initialize the database connection (I use the Sequelize ORM). This is done in a file (db.js) required from the application main file (app.js):

db.js

async function run() {
  try {
    // Creates database if it doesn't exist
    await DB_init();
  
    // Test database connection
    await DB_test();

    // Connection was OK, sync tables and relationships
    await DB_sync();

    // Check if the DB is empty and, in this case, fill the basic data
    await DB_init_values();
  } catch(error => {
    log.error("Couldn't connect to the database '"+dbName+"':", error);

    process.exit(1);
  }
}

// Init the DB
run();

This works, but now that I have to add more tests, I'd like to refactor this code to avoid the added artificial delay. How could I wait for the database initialization code to be finished before starting the tests? It seems that it's not possible to require a module synchronally, is it?

Cheers,

0 Answers
Related