Clearing tables before each test - NestJS, typeORM & Postgres

Clearing tables before each test - NestJS,  typeORM &  Postgres

We recently migrated ToolJet server from Ruby on Rails to NestJS. We had to make some changes to clear the tables before running every test.

Why should we clean databases before running every tests?
Let's say we are testing the endpoint to archive a user, we will create a new user and hit the endpoint to mark the user as archived. Our second test makes sure that active users can login. If the first test is run before the second, everything works as expected but if the second test is run first, the test will fail. We can avoid this scenario by cleaning the tables before every test.

How?
Define an helper function to clear the tables.

export async function clearDB() {
  const entities = getConnection().entityMetadatas;
  for (const entity of entities) {
    const repository = await getConnection().getRepository(entity.name);
    await repository.query(`TRUNCATE ${entity.tableName} RESTART IDENTITY CASCADE;`);
  }
}

and use the afterEach callback to invoke the clearDB function.

import * as request from 'supertest';
import { INestApplication } from '@nestjs/common';
import { clearDB } from '../test.helper';

describe('users controller', () => {
  let app: INestApplication;

  afterEach(async () => {
    await clearDB();
  });

  beforeAll(async () => {
    app = await createNestAppInstance();
  });
}

It is also recommended to drop the database, create the database and run the migrations before running the test suite. You can use the dropdb and createdb commands of postgres to do this.

We would love you to check out ToolJet on GitHub: https://github.com/ToolJet/ToolJet/