✅ Vitest - Configurazione Completata
📦 Pacchetti Installati
npm install -D vitest @vitest/ui jsdom @testing-library/react @testing-library/jest-domDipendenze
- vitest
^3.2.4- Framework di testing veloce e moderno - @vitest/ui
^3.2.4- Interfaccia grafica per test - jsdom
^27.0.0- Ambiente DOM per test - @testing-library/react
^16.3.0- Utilities per testare componenti React - @testing-library/jest-dom
^6.9.1- Matcher aggiuntivi per DOM
📁 File Creati
Configurazione
vitest.config.ts- Configurazione Vitest- Environment: jsdom
- Setup file: tests/setup.ts
- Pattern:
tests/**/*.test.{ts,tsx}eapp/**/*.test.{ts,tsx} - Coverage: v8 provider
tests/setup.ts- Setup globale per tutti i test- Mock di localStorage
- Mock di BroadcastChannel
- Mock di fetch
- Cleanup automatico dopo ogni test
- Matcher di jest-dom
Test Files
tests/auth.api.test.ts- Test API di autenticazione- ✅ 8 test per funzioni API
- Test di validazione Zod
- Mock di fetch
- Test di gestione errori
tests/auth.schema.test.ts- Test schemi Zod- ✅ 20 test per validazione schemi
- Test di tutti gli schemi auth
- Test di inferenza tipi TypeScript
Documentazione
docs/testing.md- Guida completa al testing- Esempi pratici
- Best practices
- Troubleshooting
- Integrazione CI/CD
🚀 Script Aggiunti a package.json
{
"scripts": {
"test": "vitest", // Watch mode interattivo
"test:ui": "vitest --ui", // UI grafica
"test:run": "vitest run", // Singola esecuzione (CI)
"test:coverage": "vitest run --coverage" // Con coverage report
}
}📊 Risultati Test
✓ tests/auth.schema.test.ts (20 tests) 11ms
✓ tests/auth.api.test.ts (8 tests) 12ms
Test Files 2 passed (2)
Tests 28 passed (28)
Duration 829msBreakdown
tests/auth.api.test.ts (8 test)
- ✅ Validazione input login con Zod
- ✅ Login con credenziali valide
- ✅ Gestione errori API (401)
- ✅ Logout DELETE request
- ✅ Lista aziende
- ✅ Validazione id azienda
- ✅ Impostazione azienda attiva
- ✅ Classe ApiError personalizzata
tests/auth.schema.test.ts (20 test)
✅ LoginRequestSchema - 5 test
- Dati validi
- Recaptcha opzionale
- Username vuoto
- Password vuota
- Campi mancanti
✅ LoginResponseSchema - 4 test
- Redirect main
- Redirect module con modulo
- Tutti i 7 tipi di redirect
- Redirect non valido
✅ CompanySchema - 3 test
- Dati validi
- Id non numerico
- Name non stringa
✅ SetCompanyRequestSchema - 3 test
- Id positivo valido
- Id zero non valido
- Id negativo non valido
✅ UserSettingsSchema - 4 test
- Impostazioni complete
- Array moduli vuoto
- Id company non numerico
- Modulo senza campi obbligatori
✅ Type Inference - 1 test
- Inferenza tipi TypeScript
🎯 Copertura del Codice
Per generare il report di coverage:
npm run test:coverageOutput sarà in:
- Console (formato testo)
coverage/index.html(interattivo)
🖥️ UI Mode
Per esplorare i test in modalità grafica:
npm run test:uiApre interfaccia web su http://localhost:51204 con:
- Esecuzione interattiva
- Filtri e ricerca
- Visualizzazione risultati
- Console logs
- Coverage grafici
🔄 Workflow di Sviluppo
Durante lo Sviluppo
npm testModalità watch: i test si riavviano automaticamente ad ogni modifica.
Prima del Commit
npm run test:runEsegue tutti i test una volta per verificare che passino.
Debug Test
npm run test:uiUsa l'interfaccia grafica per debuggare test specifici.
Verifica Coverage
npm run test:coverageControlla la copertura del codice testato.
📝 Come Scrivere Nuovi Test
1. Test API
Crea file app/api/[nome].api.test.ts:
import { describe, it, expect, vi, beforeEach } from "vitest";
import { myApiFunction } from "./[nome].api";
const mockFetch = vi.fn();
global.fetch = mockFetch;
describe("myApiFunction", () => {
beforeEach(() => {
mockFetch.mockReset();
});
it("dovrebbe fare qualcosa", async () => {
mockFetch.mockResolvedValueOnce({
json: async () => ({ success: true }),
ok: true,
});
const result = await myApiFunction();
expect(result.success).toBe(true);
});
});2. Test Schema Zod
Crea file tests/[nome].schema.test.ts:
import { describe, it, expect } from "vitest";
import { MySchema } from "@/schemas/[nome].schema";
describe("MySchema", () => {
it("dovrebbe validare dati corretti", () => {
const result = MySchema.safeParse({ field: "value" });
expect(result.success).toBe(true);
});
});3. Test Componenti React
Crea file app/components/[Nome].test.tsx:
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import { MyComponent } from "./[Nome]";
describe("MyComponent", () => {
it("dovrebbe renderizzare correttamente", () => {
render(<MyComponent />);
expect(screen.getByText("Testo")).toBeInTheDocument();
});
});🔧 Mock Disponibili
Grazie a tests/setup.ts, hai accesso automatico a:
localStorage
localStorage.setItem("key", "value");
localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();BroadcastChannel
const channel = new BroadcastChannel("test");
channel.postMessage({ type: "message" });
channel.close();fetch
global.fetch = vi.fn();🎓 Best Practices Implementate
✅ Globals Enabled - describe, it, expect disponibili senza import ✅ Setup File - Configurazione centralizzata ✅ Cleanup Automatico - React Testing Library cleanup dopo ogni test ✅ Mock Predefiniti - localStorage, BroadcastChannel, fetch ✅ jest-dom Matchers - Matcher aggiuntivi per testing DOM ✅ Path Aliases - Supporto per alias TypeScript ✅ Coverage Configuration - Setup completo per coverage reports
📚 Risorse
✨ Prossimi Passi
Aggiungi test per componenti React
- Login form
- Companies list
- AuthenticatedLayout
Test di integrazione
- Flusso completo login → companies → settings
- Multi-tab synchronization
Test E2E (opzionale)
- Considera Playwright o Cypress per test end-to-end
CI/CD Integration
- Aggiungi
npm run test:runalla pipeline - Genera coverage report nei PR
- Aggiungi
🎉 Conclusione
Vitest è stato configurato con successo! Hai:
- ✅ 28 test funzionanti
- ✅ Mock globali configurati
- ✅ UI mode disponibile
- ✅ Coverage reporting pronto
- ✅ Documentazione completa
Comando rapido per verificare tutto:
npm run test:runBuon testing! 🚀