import { INestApplication } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { Test, TestingModule } from '@nestjs/testing'; import { AppModule } from '../src/app.module'; import { UsersService } from '../src/modules/users/services/users.service'; import { CreateUserDto } from '../src/modules/users/dto/create-user.dto'; import { AuthService } from '../src/modules/auth/services/auth.service'; import { ValidationPipe } from '@nestjs/common'; import { v4 as uuidv4 } from 'uuid'; /** * Create a test application */ export async function createTestApp(): Promise { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); const app = moduleFixture.createNestApplication(); // Apply the same middleware as in main.ts app.useGlobalPipes( new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true, }), ); // Set global prefix as in main.ts app.setGlobalPrefix('api'); await app.init(); return app; } /** * Create a test user */ export async function createTestUser(app: INestApplication) { const usersService = app.get(UsersService); const createUserDto: CreateUserDto = { name: `Test User ${uuidv4().substring(0, 8)}`, githubId: `github-${uuidv4().substring(0, 8)}`, avatar: 'https://example.com/avatar.png', metadata: { email: 'test@example.com' }, }; return await usersService.create(createUserDto); } /** * Generate JWT tokens for a user */ export async function generateTokensForUser(app: INestApplication, userId: string) { const authService = app.get(AuthService); return await authService.generateTokens(userId); } /** * Clean up test data */ export async function cleanupTestData(app: INestApplication, userId: string) { const usersService = app.get(UsersService); try { await usersService.remove(userId); } catch (error) { console.error(`Failed to clean up test user ${userId}:`, error.message); } }