β 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! π