1

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.

mrhassan
  • 196
  • 1
  • 10

1 Answers1

1

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

Mark Wubben
  • 3,329
  • 1
  • 19
  • 16
  • thanks. I have tried that using `.before` , but the database initialisation actually sets a global variable `global.db`. so when i try run the tests that uses `global.db` from a different file it fails to read from that. – mrhassan May 26 '20 at 14:22
  • Yes, because each file runs in its own process. – Mark Wubben May 29 '20 at 09:03