NodeJS 如何在NestJS和TypeORM中每次集成测试后清除数据库?

wgx48brx  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(172)

我使用TypeORMModule为DataSource提供配置:

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `.env.${process.env.NODE_ENV}`,
    }),
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return {
          type: 'postgres',
          // host has to be the container name of the database
          host: config.get<string>('POSTGRES_HOST'),
          port: parseInt(config.get('POSTGRES_PORT')),
          username: config.get<string>('POSTGRES_USER'),
          password: config.get<string>('POSTGRES_PASSWORD'),
          database: config.get<string>('POSTGRES_DB'),
          synchronize: true,
          entities: [User],
        };
      },
    }),
    UsersModule,
  ],
})

如何为每个测试清除数据库?

brvekthn

brvekthn1#

你可以写一个实用函数来truncates所有的数据库表:

async function clearDatabase(app: INestApplication): Promise<void> {
    const entityManager = app.get<EntityManager>(EntityManager);
    const tableNames = entityManager.connection.entityMetadatas
        .map((entity) => entity.tableName)
        .join(', ');

    await entityManager.query(
        `truncate ${tableNames} restart identity cascade;`,
    );
}

然后在你的测试文件中,你只需要使用afterEach调用这个函数:

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

    beforeAll(async () => {
        const appModule = await Test.createTestingModule({
            imports: [DatabaseModule],
        }).compile();

        app = appModule.createNestApplication();
        await app.init();
    });

    afterEach(async () => {
        await clearDatabase(app);
        await app.close();
    });
});

相关问题