eletrotupi / tcc/ api/tests/test-helper.tsd3859d7a3aea712c026e40c147d5359d66f841c7
1.5 KB | 53 lines Raw
1
import { PrismaClient } from '@prisma/client';
2
import { PrismaPg } from '@prisma/adapter-pg';
3
import 'dotenv/config';
4

5
let prismaTestClient: PrismaClient | null = null;
6

7
export function getTestPrisma(): PrismaClient {
8
  if (!prismaTestClient) {
9
    // Use test database URL
10
    const connectionString = process.env.DATABASE_URL || 'postgres://user:password@localhost:5430/orbit_test';
11
    const adapter = new PrismaPg({ connectionString });
12
    prismaTestClient = new PrismaClient({ adapter });
13
  }
14
  return prismaTestClient;
15
}
16

17
export async function cleanupTestDb() {
18
  const prisma = getTestPrisma();
19

20
  // Delete in correct order due to foreign keys
21
  // Add more tables as they're added to schema
22
  try {
23
    // When we add more models, delete them here in reverse order of dependencies
24
    await prisma.user.deleteMany({});
25
  } catch (err) {
26
    console.error('Error cleaning test DB:', err);
27
  }
28
}
29

30
export async function disconnectTestDb() {
31
  if (prismaTestClient) {
32
    await prismaTestClient.$disconnect();
33
    prismaTestClient = null;
34
  }
35
}
36

37
// Helper to create test users
38
export async function createTestUser(data?: {
39
  email?: string;
40
  firstName?: string;
41
  lastName?: string;
42
  encryptedPassword?: string;
43
}) {
44
  const prisma = getTestPrisma();
45
  return await prisma.user.create({
46
    data: {
47
      email: data?.email || 'test@example.com',
48
      firstName: data?.firstName || 'Test',
49
      lastName: data?.lastName || 'User',
50
      encryptedPassword: data?.encryptedPassword || '$2a$10$test'
51
    }
52
  });
53
}