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