Skip to content

✅ Vitest - Configurazione Completata

📦 Pacchetti Installati

bash
npm install -D vitest @vitest/ui jsdom @testing-library/react @testing-library/jest-dom

Dipendenze

  • 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

  1. vitest.config.ts - Configurazione Vitest

    • Environment: jsdom
    • Setup file: tests/setup.ts
    • Pattern: tests/**/*.test.{ts,tsx} e app/**/*.test.{ts,tsx}
    • Coverage: v8 provider
  2. 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

  1. 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
  2. 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

  1. docs/testing.md - Guida completa al testing
    • Esempi pratici
    • Best practices
    • Troubleshooting
    • Integrazione CI/CD

🚀 Script Aggiunti a package.json

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  829ms

Breakdown

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:

bash
npm run test:coverage

Output sarà in:

  • Console (formato testo)
  • coverage/index.html (interattivo)

🖥️ UI Mode

Per esplorare i test in modalità grafica:

bash
npm run test:ui

Apre interfaccia web su http://localhost:51204 con:

  • Esecuzione interattiva
  • Filtri e ricerca
  • Visualizzazione risultati
  • Console logs
  • Coverage grafici

🔄 Workflow di Sviluppo

Durante lo Sviluppo

bash
npm test

Modalità watch: i test si riavviano automaticamente ad ogni modifica.

Prima del Commit

bash
npm run test:run

Esegue tutti i test una volta per verificare che passino.

Debug Test

bash
npm run test:ui

Usa l'interfaccia grafica per debuggare test specifici.

Verifica Coverage

bash
npm run test:coverage

Controlla la copertura del codice testato.

📝 Come Scrivere Nuovi Test

1. Test API

Crea file app/api/[nome].api.test.ts:

typescript
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:

typescript
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:

typescript
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

typescript
localStorage.setItem("key", "value");
localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();

BroadcastChannel

typescript
const channel = new BroadcastChannel("test");
channel.postMessage({ type: "message" });
channel.close();

fetch

typescript
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

  1. Aggiungi test per componenti React

    • Login form
    • Companies list
    • AuthenticatedLayout
  2. Test di integrazione

    • Flusso completo login → companies → settings
    • Multi-tab synchronization
  3. Test E2E (opzionale)

    • Considera Playwright o Cypress per test end-to-end
  4. CI/CD Integration

    • Aggiungi npm run test:run alla pipeline
    • Genera coverage report nei PR

🎉 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:

bash
npm run test:run

Buon testing! 🚀

Documentazione Elerama Frontend