Search code examples
node.jsdatabasesequelize.jsava

AVA Test Fails in case of accessing global variable


We've recently started migrating tests for database models.

Facing an issue while trying to separate out different type of tests in different files.

I am writing some AVA unit tests In one file test_1.js it is,

const test = require('ava');

const sDB = require('../services/serviceDB');

const config = require('../../config').production;
const { CONFIG_RDS } = config;


let x = 1;

test.before(async (t) => {
  t.context.log = console.log;
// following line connects with database and sets global.db
    await loaderDB.connect(CONFIG);

  })

test('Test 1 - to access database',async(t)=>{
    // test some functionality that accesses global.db
    // it passes
})


On the other file test_2.js

const test = require('ava');

const sDB = require('../services/serviceDB');

const config = require('../../config').production;
const { CONFIG_RDS } = config;


let x = 1;

test.before(async (t) => {
  t.context.log = console.log;
  // wait for db to be connected
   await timeout(4000) // custom timeout that awaits

  })

test('Test 2 - to access database',async(t)=>{
    // test some functionality that accesses global.db
    // it FAILS
    // It returns exception that global.db is undefined
})

Thanks for your help in advance.


Solution

  • Each test file runs in its own process, so you need to connect to the database in each test file.