0

I'm trying to do integration testing against a real database and I'm new to jest and knex..

Here's what I have so far:

describe('FooRepository', () => {
  let dbName;
  let conn;

  beforeAll(async () => {
    conn = getConnection();
    dbName = cryptoRandomString({ length: 5, characters: 'abcdefghijklmnopqrstuvwxyz' });
    await conn.raw(`CREATE DATABASE ${dbName}`);
    Model.knex(conn);
  });

  afterAll(async () => {
    await conn.raw(`DROP DATABASE ${dbName}`);
    await conn.destroy();
  });

  beforeEach(async () => {
    await conn.migrate.latest();
  });

  afterEach(async () => {
    await conn.migrate.rollback();
  });

  describe('getFooByID', () => {
    // test getFooByID()
  })
})

How can I put this dbName, conn, and those before/after actions into somewhere reusable? Thanks

isherwood
  • 58,414
  • 16
  • 114
  • 157
user1354934
  • 8,139
  • 15
  • 50
  • 80
  • By 'reusable' do you mean to reuse in other adjacent test files? – SarathMS Jan 16 '20 at 21:04
  • 1
    is there any specific reason you can't just stick that code in a function & reuse it when you need it? – Klaycon Jan 16 '20 at 21:06
  • also be aware that by default `beforeEach`, `afterEach`, etc etc apply to *all* tests defined in the current scope, so it's already reused by default, if you need it reused for other tests just move it up a scope – Klaycon Jan 16 '20 at 21:07

1 Answers1

0

You could use globalSetup and globalTeardown to setup things globally which can be used across tests. More info here -

https://jestjs.io/docs/en/configuration#globalsetup-string

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35