🧪 Testing
Rial tiene cobertura de tests en el backend (Jest) y en el frontend (Playwright E2E). Esta guía explica cómo correr los tests existentes, dónde viven y cómo escribir nuevos.
Backend — Jest (rial-backend)
Tipos de tests
| Tipo | Ubicación | Runner |
|---|---|---|
| Unit tests | src/**/*.spec.ts | yarn test |
| Integration tests | test/integration/*.integration-spec.ts | yarn test:integration |
| E2E tests | test/*.e2e-spec.ts | yarn test:e2e |
Correr los tests
# Desde rial-backend/
# Todos los unit tests
yarn test
# Unit tests en modo watch (re-corre cuando cambia un archivo)
yarn test:watch
# Tests con cobertura de código
yarn test:cov
# Integration tests (requiere base de datos local)
yarn test:integration
# E2E tests
yarn test:e2eEstructura de un unit test
Los unit tests se ubican junto al archivo que testean (*.spec.ts):
// src/lib/policies/project.policies.spec.ts
describe("ProjectPolicies", () => {
describe("canCreateProject", () => {
it("should allow COMPANY_ADMIN with PROJECT_CREATOR permission", () => {
const user = mockUser({
role: "COMPANY_ADMIN",
permissions: ["PROJECT_CREATOR"],
});
expect(canCreateProject(user)).toBe(true);
});
it("should deny user without PROJECT_CREATOR permission", () => {
const user = mockUser({ role: "COMPANY_ADMIN", permissions: [] });
expect(canCreateProject(user)).toBe(false);
});
});
});Estructura de un integration test
Los integration tests usan una base de datos real (DATABASE_URL_TEST apuntando al bucket rial_test):
// test/integration/project-creation.integration-spec.ts
describe("ProjectCreation (integration)", () => {
let app: INestApplication;
let prisma: PrismaClient;
beforeAll(async () => {
app = await createTestApp();
prisma = new PrismaClient();
});
afterAll(async () => {
await prisma.$disconnect();
await app.close();
});
it("should create a BATCH project from Excel", async () => {
const seed = await seedProjectCreationData(prisma);
const response = await request(app.getHttpServer())
.post("/api/v1/projects/batch")
.set("Authorization", `Bearer ${seed.userToken}`)
.send(seed.payload);
expect(response.status).toBe(201);
expect(response.body.projectFolder).toBeDefined();
});
});Helpers disponibles
| Helper | Descripción |
|---|---|
test/mock/mock.factory.ts | Crea objetos mock (usuarios, proyectos, etc.) |
test/helpers/policy-test-context.ts | Contexto de usuario para tests de policies |
test/helpers/test-user.ts | Crea tokens JWT de test |
test/builders/project-creation.builder.ts | Builder para payloads de creación de proyecto |
test/helpers/project-creation-seed.ts | Seed de datos para tests de creación |
Escribir nuevos tests — Skill disponible
Para escribir tests nuevos siguiendo las convenciones del proyecto, consulta el skill:
.cursor/skills/rial-backend-tests/SKILL.mdEl skill incluye ejemplos de:
- Unit tests de policies y guards
- Tests de integración con builders y seeds
- Mocks de servicios externos (GCS, Cloud Tasks)
Frontend — Playwright E2E (rial-frontend)
Configuración
# Instalar dependencias de Playwright
cd rial-frontend
yarn playwright install
# Correr todos los E2E tests
yarn playwright test
# Correr en modo UI (visual, con debugging)
yarn playwright test --ui
# Ver reporte HTML del último run
yarn playwright show-reportEstructura de un E2E test
// tests/project-creation.spec.ts
import { test, expect } from "@playwright/test";
test.describe("Project Creation", () => {
test.beforeEach(async ({ page }) => {
await page.goto("/auth/login");
await page.fill('input[type="email"]', process.env.TEST_USER_EMAIL!);
await page.fill('input[type="password"]', process.env.TEST_USER_PASSWORD!);
await page.click('button[type="submit"]');
await page.waitForURL("**/dashboard");
});
test("should show project type selector", async ({ page }) => {
await page.goto("/projects/create");
await expect(page.locator("text=Faceswap")).toBeVisible();
await expect(page.locator("text=Generación masiva")).toBeVisible();
await expect(page.locator("text=Producto")).toBeVisible();
});
test("should navigate to BATCH form", async ({ page }) => {
await page.goto("/projects/create");
await page.click("text=Generación masiva");
await expect(page.locator("text=Subir Excel")).toBeVisible();
});
});Variables de entorno para E2E
# .env.test en rial-frontend/
TEST_USER_EMAIL=test@empresa.cl
TEST_USER_PASSWORD=test-password
NEXT_PUBLIC_API_URL=http://localhost:3001Ambientes de test
| Tipo | Base de datos | Bucket GCS | Cuándo se usa |
|---|---|---|---|
| Unit tests | Mock (sin BD) | Mock | PR validation, desarrollo |
| Integration tests | Supabase test project | rial_test | PR validation en CI |
| E2E tests | Staging (staging.rial-ai.com) | rial_staging | QA manual, regression |
CI — Tests automáticos
Los tests se corren automáticamente en GitHub Actions en cada PR:
# .github/workflows/unit-and-integration-tests.yml
on:
pull_request:
branches: [develop]
jobs:
test:
steps:
- yarn test # Unit tests
- yarn test:integration # Integration testsEl workflow de CI no corre los E2E de Playwright — esos se corren manualmente antes de releases importantes.
Checklist antes de hacer PR
- Todos los unit tests pasan:
yarn test - Todos los integration tests pasan:
yarn test:integration - No hay errores de TypeScript:
yarn tsc --noEmit - El linter no tiene errores:
yarn lint - Si cambiaste el schema de BD: corriste la migración y regeneraste el cliente Prisma
Last updated on