DEV Community

Discussion on: Tests with Jest and TypeORM

Collapse
 
hantsy profile image
Hantsy Bai • Edited
 await repository.query(`DELETE FROM ${entity.tableName}`);
Enter fullscreen mode Exit fullscreen mode

This will be a problem when you set the relations between tables.

Collapse
 
kentbull profile image
Kent Bull

You can just drop the schema and recreate it from migrations. See my other response.

Collapse
 
oxilor profile image
oxilor • Edited

You can do the following way:

afterEach(async () => {
  const entities = connection.entityMetadatas;
  for (const entity of entities) {
    const repository = connection.getRepository(entity.name);
    const schemaPrefix = entity.schema ? `${entity.schema}.` : '';
    await repository.query(
      `TRUNCATE ${schemaPrefix}${entity.tableName} RESTART IDENTITY CASCADE`
    );
  }
});
Enter fullscreen mode Exit fullscreen mode

The TypeORM also has the synchronize method, so you can simplify this code:

afterEach(async () => {
  await connection.synchronize(true);
});
Enter fullscreen mode Exit fullscreen mode

true means that TypeORM will drop all tables before syncing.