From 52d74a754c7c52bbf0f7cf651dfff4111b9e9824 Mon Sep 17 00:00:00 2001 From: Mathis HERRIOT <197931332+0x485254@users.noreply.github.com> Date: Fri, 16 May 2025 19:07:09 +0200 Subject: [PATCH] feat(tests): add utility functions for testing with NestJS Add test utilities to facilitate creating test apps, test users, generating tokens, and cleaning up test data in the backend codebase. --- backend/test/test-utils.ts | 72 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 backend/test/test-utils.ts diff --git a/backend/test/test-utils.ts b/backend/test/test-utils.ts new file mode 100644 index 0000000..3b7363f --- /dev/null +++ b/backend/test/test-utils.ts @@ -0,0 +1,72 @@ +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); + } +} \ No newline at end of file