eletrotupi / tcc/ api/tests/test-helper.ts0e72d1f6b4b7e0e42b7922b3db5fb7da683e8c6d
1.3 KB | 41 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: {
22
    email?: string
23
    firstName?: string
24
    lastName?: string
25
    password?: string
26
    pushToken?: string
27
    notificationsEnabled?: boolean
28
  } = {}
29
) {
30
  const { password, pushToken, notificationsEnabled, ...rest } = overrides
31
  return prisma.user.create({
32
    data: {
33
      email: rest.email ?? 'test@example.com',
34
      firstName: rest.firstName ?? 'Test',
35
      lastName: rest.lastName ?? 'User',
36
      encryptedPassword: await bcrypt.hash(password ?? 'password123', 10),
37
      ...(pushToken !== undefined && { pushToken }),
38
      ...(notificationsEnabled !== undefined && { notificationsEnabled }),
39
    },
40
  })
41
}