import { INestApplication } from '@nestjs/common'; import { FastifyAdapter, NestFastifyApplication, } from '@nestjs/platform-fastify'; import { Test } from '@nestjs/testing'; import { randomUUID } from 'crypto'; import request from 'supertest'; import { AppModule } from '../src/app.module'; import { configureApp } from '../src/configure-app'; export const PASSWORD = 'Correct-Horse-Battery-42'; export interface TestUser { id: string; username: string; token: string; } export async function createTestApp( env: Record = {}, setup: (app: NestFastifyApplication) => void = () => undefined, ): Promise<{ app: INestApplication; server: any; }> { const saved = { ...process.env }; Object.assign(process.env, env); let app: NestFastifyApplication; try { const moduleRef = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleRef.createNestApplication( new FastifyAdapter(), ); } finally { process.env = saved; } configureApp(app); setup(app); await app.listen(0, '127.0.0.1'); return { app, server: app.getHttpServer() }; } export function basic(username: string, password: string): string { return `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`; } export function bearer(user: TestUser): string { return `Bearer ${user.token}`; } export async function login( server: any, username: string, password = PASSWORD, ): Promise { const res = await request(server) .post('/api/v1/auth/sessions') .set('Authorization', basic(username, password)) .expect(201); return res.body.token; } export async function registerUser( server: any, label: string, ): Promise { const username = `u_${label}_${randomUUID().slice(0, 8)}`; const res = await request(server) .post('/api/v1/users') .send({ username, display_name: `User ${label}`, password: PASSWORD }) .expect(201); return { id: res.body.id, username, token: await login(server, username) }; }