eletrotupi / tcc/ api/tests/test-helper.tsfd61f8e0e9ed5e94cb9fa0e56e8bfd87c96c8088
1.0 KB | 31 lines Raw
1
import { PrismaClient } from '@prisma/client'
2
import { PrismaPg } from '@prisma/adapter-pg'
3
import jwt from 'jsonwebtoken'
4
import bcrypt from 'bcryptjs'
5

6
export function buildPrisma(): PrismaClient {
7
  const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! })
8
  return new PrismaClient({ adapter })
9
}
10

11
export async function cleanupTestDb(prisma: PrismaClient) {
12
  await prisma.$executeRawUnsafe('TRUNCATE users CASCADE')
13
}
14

15
export function generateTestToken(userId: number, email: string): string {
16
  return jwt.sign({ userId, email }, process.env.JWT_SECRET!, { expiresIn: '1h' })
17
}
18

19
export async function createTestUser(
20
  prisma: PrismaClient,
21
  overrides: { email?: string; firstName?: string; lastName?: string; password?: string } = {}
22
) {
23
  return prisma.user.create({
24
    data: {
25
      email: overrides.email ?? 'test@example.com',
26
      firstName: overrides.firstName ?? 'Test',
27
      lastName: overrides.lastName ?? 'User',
28
      encryptedPassword: await bcrypt.hash(overrides.password ?? 'password123', 10),
29
    },
30
  })
31
}