Volver a la documentación
Guía 11

Testing

Simmetric Chat usa Jest 30 con transformación @swc/jest (unit + integration) y Playwright (E2E), orquestados por Turborepo. El jest.config.cjs raíz agrega los 5 proyectos (shared, server, frontend, collector, widget).

3 min de lectura

Simmetric Chat usa Jest 30 con transformación @swc/jest (unit + integration) y Playwright (E2E), orquestados por Turborepo. El jest.config.cjs raíz agrega los 5 proyectos (shared, server, frontend, collector, widget).

Niveles

NivelRunnerDBScope
UnitJest 30 + @swc/jestmock Prisma (sin DB)servicios, utilidades, validación
IntegrationJest 30 + supertest 7PostgreSQL worker realroutes, middleware, flujos DB
E2EPlaywrightapp completaUI user-facing (13 spec)

Unit test

Mock de Prisma via jest.mock (sin DB real). Tests de: servicios (RAG, backup, encryption, DLP, agent budget), utilidades (RBAC, license, chunker), schema Zod, webhook dispatch. Server unit: mock moduleNameMapper para las dependencias pesadas (uuid, jsdom, pdfjs-dist, pg-boss...) y mapping @simmetric-chat/shared → shared/dist (rebuild shared tras editar - gotcha turbo ^build; frontend/widget mapean la source).

bash
pnpm test               # los 5 package via turbo (Postgres-free)
pnpm test:all           # mismas suites via jest.config.cjs (Jest puro)
pnpm --filter server test
pnpm --filter shared test

Convenciones: archivos *.test.ts en __tests__/ junto al source (frontend *.test.tsx en entorno jsdom). Snapshot solo para outputs deterministas (no para LLM). Usa jest.mock('../prisma') para aislar la DB; un archivo server unit empieza con import "./helpers/setupEnv".

Integration test

Worker DB PostgreSQL real en localhost:5434 (para .env.test). Template simmetricchat_test_template clonado por-test-file (SHA-256 del path) para aislamiento. Tests de routes Express (supertest 7), middleware (auth, RBAC, license, rate limit), flujos DB completos (workspace, chat, documentos, backup restore). El collector tiene una suite integration dedicada en pgvector_test puerto 5433 (jest.config.integration.cjs).

Setup:

  • Variables env de test (DB test, JWT_SECRET test, secretos compartidos - trazadas en packages/server/.env.test).
  • Migraciones aplicadas al template (jest.globalSetup.js: migrate deploy + seed); cada archivo de test clona una DB fresh; el teardown droppea el template.
  • Runs secuenciales (las suites pueden leer el DATABASE_URL cacheado - deuda conocida).
bash
pnpm --filter server test:integration          # --forceExit incluido
pnpm --filter collector test:integration

E2E (Playwright)

13 spec en e2e/. Cubren flujos user-facing: auth/admin, chat streaming, chat edit/regenerate, document upload → RAG, unified upload destinations, widget embed, MCP install (marketplace lifecycle), MCP pin/use, admin settings nav, synthesis run, RBAC UI (project sidebar), theme switch.

bash
pnpm test:e2e
# con UI: pnpm exec playwright test --ui

Prerrequisitos: app up (pnpm dev o compose), DB migrated, @simmetric-chat/shared + frontend build, browsers instalados (pnpm exec playwright install). Playwright arranca por sí solo los 3 web server (backend tsx, frontend vite preview, widget - todos reuseExistingServer); el globalSetup es idempotente (setup wizard → admin/admin123, widget E2E + E2E_WIDGET_ID, reset mustChangePassword). Config en playwright.config.ts (30s timeout, retries 2). Las spec enterprise-gated se self-skippean sin LICENSE_KEY.

Coverage

Ningún umbral de coverage configurado en los config Jest y la coverage no es un gate CI; el gate de calidad más cercano es el test-count guard (cap 3900 declaraciones para la suite community). Reports locales:

bash
pnpm test:all -- --coverage
pnpm --filter server test -- --coverage

Foco de escritura en los servicios críticos: agent orchestrator, hybridSearch, backup, encryption, license, RBAC.

Test de flujos críticos (checklist)

  • RAG híbrido: vector + FTS + RRF fusion + fallback archive (D-07) + guard embedding mismatch (D-01) + metadata filtering (pre-filter + SQL predicate + backstop server-side).
  • Agent ReAct: loop detection, circuit breaker unknown-tool (BOT-03), budget wallclock/token/context, per-user concurrency, fallback provider.
  • Widget: sesión anónima + expiración, rate limit doble layer (burst per-widget + daily per-widget+IP), lead capture, IDOR prevention (whitelist WidgetWorkspace), proxy SSE transparente.
  • Backup: dump → archive → checksum → upload retry → restore atomicity (psql single-transaction) + retention.
  • MCP: transport fallback (D-09), install/uninstall, pin resolution (union strict), health check (pg-boss cron, staleness a 3 niveles).
  • License: graceful degradation Enterprise→Community, gating 402, límites numéricos.

Debug test

bash
pnpm --filter server test -- src/__tests__/auth.test.ts      # por archivo (posicional)
pnpm --filter server test -- -t "nombre del test"            # por nombre
pnpm --filter server test:integration -- --runInBand         # serial para DB
DEBUG=1 pnpm test:e2e -- --headed

CI

Turborepo cachea test; pipeline típica: lint → typecheck → test → test:integration → build → test:e2e. El worker DB para integration requiere un service PostgreSQL en CI (pgvector/pgvector:pg16). Jobs test-relevant: test-unit (+ air-gap grep gate + FTS locale gate + test-count guard), test-airgap (NETWORK_EGRESS_BLOCKED=1), test-e2e, build (+ freshness check).