integration-test-db.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { DataSource } from 'typeorm';
  2. import { beforeEach, afterEach } from 'vitest';
  3. import { AppDataSource, EntityTarget, initializeDataSource } from '@d8d/shared-utils';
  4. /**
  5. * 集成测试数据库工具类 - 使用真实PostgreSQL数据库
  6. * 通用版本,不依赖特定实体
  7. */
  8. export class IntegrationTestDatabase {
  9. /**
  10. * 清理集成测试数据库
  11. */
  12. static async cleanup(): Promise<void> {
  13. if (AppDataSource.isInitialized) {
  14. await AppDataSource.destroy();
  15. }
  16. }
  17. /**
  18. * 获取当前数据源
  19. */
  20. static async getDataSource(): Promise<DataSource> {
  21. if (!AppDataSource.isInitialized) {
  22. await AppDataSource.initialize();
  23. }
  24. return AppDataSource;
  25. }
  26. /**
  27. * 使用特定实体初始化数据源
  28. */
  29. static async initializeWithEntities(entities: EntityTarget[]): Promise<DataSource> {
  30. initializeDataSource(entities);
  31. return await this.getDataSource();
  32. }
  33. }
  34. /**
  35. * 集成测试数据库生命周期钩子(带实体初始化)
  36. */
  37. export function setupIntegrationDatabaseHooksWithEntities(entities: EntityTarget[]) {
  38. beforeEach(async () => {
  39. await IntegrationTestDatabase.initializeWithEntities(entities);
  40. });
  41. afterEach(async () => {
  42. await IntegrationTestDatabase.cleanup();
  43. });
  44. }