Jest: How to share DB connection across files before running all tests?

Viewed 289

Here's an example.

There are 3 test files

test
 - customer.test.ts
 - user.test.ts
 - staff.test.ts

Each of them needs a DB connection (whatever DB and ORM you use), so you'll see the following lines in all of the test files.

describe('staff.test.ts', () => {
  let testDb;

  beforeAll(async () => {
    testDb = await getTestDb(); // This returns a DB connection
  });

  afterEach(async () => {
    await testDb.synchronize(true);
  });

  afterAll(async () => {
    await testDb.close();
  });

  // tests are here
});

In all the files,

  1. testDb is always instantiated with the same function (getTestDb())
  2. beforeAll, afterEach, afterAll are copied/pasted.

How can I...

  1. share an instantiated DB connection across all the files,
  2. call beforeAlland afterAll before running all the tests, and
  3. call afterEach for each test case?

It seems that globalSetup allows me to export "an async function that is triggered once before all test suites." However, I have to not only run beforeAll, but also share an instantiated DB connection.

Is it achievable? Any advice will be appreciated!

0 Answers
Related