Scegliere il livello di test
Verifica la regola di quantità da 1 a 10 isolatamente, senza DOM. Un test di componente controlla modulo, messaggi e correzione; un test di integrazione verifica il client HTTP rispetto al contratto di risposta. Riserva E2E ai flussi in cui collaborano livelli reali. [1][2]
Non esiste una proporzione universale della piramide. Investi dove le regressioni sono costose e sfuggono ai livelli inferiori. Un test del modulo nel browser non dimostra la persistenza di un ordine; l’esempio salva soltanto lo stato di presentazione.
Test unitari: contratto e limiti
src/quantity.ts
export const MAX_QUANTITY = 10;
function isDigitString(value: string): boolean {
if (value.length === 0) {
return false;
}
return !/\D/.test(value);
}
function isValidQuantity(quantity: number): boolean {
if (!Number.isSafeInteger(quantity)) {
return false;
}
if (quantity < 1) {
return false;
}
return quantity <= MAX_QUANTITY;
}
export function parseQuantity(value: string): number {
if (!isDigitString(value)) {
throw new RangeError("Enter a whole number.");
}
const quantity = Number(value);
if (!isValidQuantity(quantity)) {
throw new RangeError(`Quantity must be between 1 and ${MAX_QUANTITY}.`);
}
return quantity;
}
tests/quantity.test.ts
import { describe, expect, it } from "vitest";
import { parseQuantity } from "../src/quantity.js";
describe("parseQuantity", () => {
it.each([
{ value: "1", expected: 1 },
{ value: "10", expected: 10 },
{ value: "05", expected: 5 },
])("accepts $value as $expected", ({ value, expected }) => {
expect(parseQuantity(value)).toBe(expected);
});
it.each(["", "0", "11", "-1", "1.5", "1e1", " 2", "2x", "2\n"])(
"rejects %j",
(value) => {
expect(() => parseQuantity(value)).toThrow(RangeError);
},
);
});
parseQuantity accetta una stringa non vuota di cifre ASCII e restituisce un intero da 1 a 10; gli zeri iniziali sono ammessi. Rifiuta frazioni, notazione esponenziale, spazi e valori fuori intervallo. I casi parametrizzati coprono entrambi i limiti e gli input non validi. [1]
Non verificare quante volte viene eseguita una regex, ma il risultato o il tipo di errore. Una modifica dell’implementazione che conserva il contratto non dovrebbe rompere il test.
Given–When–Then (GWT) e Arrange–Act–Assert (AAA)
examples/stock.feature
Feature: Stock availability
Scenario: Read available stock
Given the stock API reports 3 available items
When the application requests stock availability
Then the application receives 3 as the available quantity
Given descrive il contesto iniziale, When l’azione o l’evento e Then il risultato osservabile atteso. Il test di integrazione delle scorte configura la risposta API, richiama l’adattatore e verifica il risultato. [20]
GWT è una struttura facoltativa, non un requisito di Vitest o Playwright. AAA (Arrange, Act, Assert) è altrettanto naturale nei test unitari. Gherkin e Cucumber sono opzioni per scenari di accettazione più articolati; senza definizioni dei passi corrispondenti uno scenario non è un test eseguibile. Evita commenti meccanici nei test brevi ed evidenti. [20][21]
Strumenti e configurazione
package.json
{
"name": "polprog-frontend-testing-example",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"coverage": "vitest run --coverage",
"e2e": "playwright test",
"format:check": "prettier --check ."
},
"devDependencies": {
"@playwright/test": "^1.56.1",
"@testing-library/dom": "^10.4.1",
"@testing-library/user-event": "^14.6.1",
"@types/node": "^22.0.0",
"@vitest/coverage-v8": "4.0.0",
"jsdom": "^26.1.0",
"msw": "^2.11.0",
"prettier": "^3.6.2",
"typescript": "~5.8.3",
"vite": "^7.1.0",
"vitest": "4.0.0"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"noUncheckedIndexedAccess": true,
"noEmit": true,
"types": ["vite/client", "node"],
"skipLibCheck": true
},
"include": ["src", "tests", "e2e", "*.config.ts"]
}
vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
include: ["tests/**/*.test.ts"],
coverage: {
provider: "v8",
include: [
"src/quantity.ts",
"src/stock.ts",
"src/cart.ts",
"src/schedule.ts",
],
reporter: ["text", "html"],
},
},
});
Confronti di strumenti su POLPROG: Jest vs Vitest.
Vitest si integra con Vite; Jest resta sensato in progetti esistenti con trasformazioni e suite proprie. Il runner non sostituisce il compilatore TypeScript. Esegui tsc separatamente. [3][4] [18]
L’esempio usa la sintassi di Vitest 4, Vite 7 e MSW 2 senza definirle le versioni più recenti. Installa le dipendenze, versiona il lockfile e usa npm ci in CI. Separa i test Vitest da e2e; scegli jsdom solo per il test DOM.
Test dei componenti: comportamento osservabile
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Cart quantity</title>
<link rel="stylesheet" href="/it/src/styles.css" />
</head>
<body>
<main id="cart">
<h1>Cart quantity</h1>
<form novalidate>
<label for="quantity">Quantity</label>
<input id="quantity" name="quantity" inputmode="numeric" />
<button type="submit">Save quantity</button>
<output role="status" for="quantity"></output>
</form>
</main>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
src/styles.css
body {
font-family: system-ui, sans-serif;
margin: 2rem;
}
form {
display: grid;
gap: 0.75rem;
max-width: 24rem;
}
input,
button {
font: inherit;
padding: 0.75rem;
}
input[aria-invalid="true"] {
border: 2px solid #a21a1a;
}
output {
min-height: 1.5em;
}
src/cart.ts
import { parseQuantity } from "./quantity.js";
function requireElement<T extends Element>(element: T | null): T {
if (element === null) {
throw new Error("Cart markup is incomplete.");
}
return element;
}
export function mountCart(root: HTMLElement): () => void {
const form = requireElement(root.querySelector("form"));
const input = requireElement(root.querySelector("input"));
const status = requireElement(root.querySelector("output"));
const controller = new AbortController();
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
try {
const quantity = parseQuantity(input.value);
input.removeAttribute("aria-invalid");
status.textContent = `Quantity saved: ${quantity}`;
} catch (error) {
if (!(error instanceof RangeError)) {
throw error;
}
input.setAttribute("aria-invalid", "true");
status.textContent = error.message;
input.focus();
}
},
{ signal: controller.signal },
);
return () => controller.abort();
}
src/main.ts
import { mountCart } from "./cart.js";
const root = document.querySelector<HTMLElement>("#cart");
if (!root) {
throw new Error("Cart root not found.");
}
mountCart(root);
tests/cart.test.ts
// @vitest-environment jsdom
import { screen } from "@testing-library/dom";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it } from "vitest";
import { mountCart } from "../src/cart.js";
import markup from "../index.html?raw";
let dispose: (() => void) | undefined;
beforeEach(() => {
const page = new DOMParser().parseFromString(markup, "text/html");
document.body.replaceChildren(...page.querySelectorAll("main"));
const root = document.getElementById("cart");
if (!root) {
throw new Error("Missing test fixture.");
}
dispose = mountCart(root);
});
afterEach(() => {
dispose?.();
dispose = undefined;
document.body.replaceChildren();
});
it("reports invalid quantity and lets the user correct it", async () => {
const user = userEvent.setup();
const input = screen.getByRole("textbox", { name: "Quantity" });
const save = screen.getByRole("button", { name: "Save quantity" });
await user.type(input, "0");
await user.click(save);
expect(input.getAttribute("aria-invalid")).toBe("true");
expect(document.activeElement).toBe(input);
expect(screen.getByRole("status").textContent).toContain("between");
await user.clear(input);
await user.type(input, "3");
await user.click(save);
expect(input.hasAttribute("aria-invalid")).toBe(false);
expect(screen.getByRole("status").textContent).toBe(
"Quantity saved: 3",
);
});
Il modulo contiene etichetta, pulsante, messaggio di stato e aria-invalid. Evita proprietà private e classi CSS. Testing Library cerca per ruolo e nome; user-event modella le interazioni. getBy verifica presenza immediata, queryBy assenza, findBy attende la comparsa. [5][6]
Il test copre errore, correzione, focus e rimozione di aria-invalid. Il componente restituisce una funzione di pulizia; dopo ogni test rimuoviamo listener e DOM. jsdom non riproduce tutto il layout e il motore di rendering del browser. [19]
Integrazione: risposte HTTP controllate
src/stock.ts
interface StockResponse {
available: number;
}
function isObject(value: unknown): value is object {
if (value === null) {
return false;
}
return typeof value === "object";
}
function hasAvailableField(
value: unknown,
): value is { available: unknown } {
if (!isObject(value)) {
return false;
}
return "available" in value;
}
function isNonNegativeSafeInteger(value: unknown): value is number {
if (typeof value !== "number") {
return false;
}
if (!Number.isSafeInteger(value)) {
return false;
}
return value >= 0;
}
function isStockResponse(value: unknown): value is StockResponse {
if (!hasAvailableField(value)) {
return false;
}
return isNonNegativeSafeInteger(value.available);
}
export async function fetchStock(
url: URL,
signal?: AbortSignal,
): Promise<number> {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Stock request failed: ${response.status}`);
}
const data: unknown = await response.json();
if (!isStockResponse(data)) {
throw new TypeError("Invalid stock response.");
}
return data.available;
}
tests/stock.test.ts
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, expect, it } from "vitest";
import { fetchStock } from "../src/stock.js";
const url = new URL("https://shop.example/api/stock");
const server = setupServer(
http.get(url.href, () => HttpResponse.json({ available: 3 })),
);
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it("returns validated stock", async () => {
// Given
const availableStock = 3;
server.use(
http.get(url.href, () =>
HttpResponse.json({ available: availableStock }),
),
);
// When
const available = await fetchStock(url);
// Then
expect(available).toBe(availableStock);
});
it("rejects an HTTP failure", async () => {
server.use(
http.get(url.href, () => new HttpResponse(null, { status: 503 })),
);
await expect(fetchStock(url)).rejects.toThrow("503");
});
it.each([0, Number.MAX_SAFE_INTEGER])(
"accepts a valid boundary quantity: %s",
async (available) => {
server.use(
http.get(url.href, () => HttpResponse.json({ available })),
);
await expect(fetchStock(url)).resolves.toBe(available);
},
);
it.each([
{ name: "wrong type", body: { available: "3" } },
{ name: "missing field", body: {} },
{ name: "null", body: null },
{ name: "array", body: [] },
{ name: "negative", body: { available: -1 } },
{ name: "fraction", body: { available: 1.5 } },
{
name: "unsafe integer",
body: { available: Number.MAX_SAFE_INTEGER + 1 },
},
])("rejects a broken response contract: $name", async ({ body }) => {
server.use(http.get(url.href, () => HttpResponse.json(body)));
await expect(fetchStock(url)).rejects.toThrow(TypeError);
});
it("rejects a network failure", async () => {
server.use(http.get(url.href, () => HttpResponse.error()));
await expect(fetchStock(url)).rejects.toThrow();
});
it("rejects a cancelled request", async () => {
const controller = new AbortController();
controller.abort();
await expect(fetchStock(url, controller.signal)).rejects.toMatchObject({
name: "AbortError",
});
});
fetchStock verifica response.ok e valida JSON sconosciuto. Fetch non rifiuta una promessa soltanto per lo stato 503. MSW intercetta richieste al confine di rete senza sostituire la funzione testata; copri successo, errore HTTP, contratto non valido e guasto di rete. [7] [17]
In Node, setupServer rifiuta richieste senza handler; ripristina gli handler aggiuntivi dopo ogni test. Un’API simulata non dimostra compatibilità con il servizio reale. Aggiungi test di contratto o integrazione con un backend di test; l’adattatore accetta un segnale di annullamento.
I predicati con nome separano il controllo della struttura della risposta dalla validazione numerica. Verifica il contratto dell’adattatore anche con campi mancanti, null, frazioni, numeri negativi e interi fuori dall’intervallo sicuro.
Mock, stub, spy e tempo
src/schedule.ts
export function scheduleRefresh(
refresh: () => void,
delayMs: number,
): () => void {
const timer = setTimeout(refresh, delayMs);
return () => clearTimeout(timer);
}
tests/schedule.test.ts
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { scheduleRefresh } from "../src/schedule.js";
const DELAY_MS = 300;
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("refreshes only after the delay", () => {
const refresh = vi.fn();
scheduleRefresh(refresh, DELAY_MS);
vi.advanceTimersByTime(DELAY_MS - 1);
expect(refresh).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(refresh).toHaveBeenCalledTimes(1);
});
it("does not refresh after cancellation", () => {
const refresh = vi.fn();
const cancel = scheduleRefresh(refresh, DELAY_MS);
cancel();
vi.advanceTimersByTime(DELAY_MS);
expect(refresh).not.toHaveBeenCalled();
});
Uno stub fornisce una risposta controllata; uno spy registra chiamate, spesso conservando il comportamento originale; mock indica più in generale una dipendenza sostitutiva, talvolta con aspettative. La terminologia varia. Sostituisci i confini, non la funzione testata. [3][8]
Per debounce usa vi.useFakeTimers, avanza esplicitamente il tempo e ripristina i timer reali. Con le promesse scegli le varianti asincrone appropriate. Non combinare alla cieca timer finti e attese DOM; evita pause reali e attendi le operazioni asincrone.
L’esempio indipendente programma e annulla un aggiornamento; non implementa debounce.
E2E: browser reale
playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
const baseURL = "http://127.0.0.1:4173";
export default defineConfig({
testDir: "./e2e",
forbidOnly: Boolean(process.env.CI),
retries: 0,
use: {
baseURL,
trace: "retain-on-failure",
},
projects: [{ name: "chromium", use: devices["Desktop Chrome"] }],
webServer: {
command: "npm run preview -- --host 127.0.0.1 --port 4173 --strictPort",
url: baseURL,
reuseExistingServer: false,
},
});
e2e/cart.spec.ts
import { expect, test } from "@playwright/test";
test("saves a corrected quantity with the keyboard", async ({ page }) => {
await page.goto("/");
const input = page.getByRole("textbox", { name: "Quantity" });
const status = page.getByRole("status");
await input.fill("0");
await input.press("Enter");
await expect(input).toHaveAttribute("aria-invalid", "true");
await expect(input).toBeFocused();
await expect(status).toContainText("between");
await input.fill("3");
await input.press("Enter");
await expect(status).toHaveText("Quantity saved: 3");
await expect(input).not.toHaveAttribute("aria-invalid", "true");
});
Confronti di strumenti su POLPROG: Cypress vs Playwright.
Playwright apre l’applicazione compilata, individua il campo per nome e invia con la tastiera. Le azioni attendono le condizioni di interazione e le asserzioni web riprovano fino al timeout. Non sostituirle con pause arbitrarie. [9][10]
La configurazione avvia un server a un indirizzo definito; esegui il build prima di E2E. Cypress supporta anche test di componenti ed E2E. Per ordini reali aggiungi un flusso con backend di test e dati controllati, verificando persistenza e rifiuto di richieste non autorizzate. [2][11]
Accessibilità e regressione visiva
Asserzioni su focus e ruoli semantici aiutano a individuare regressioni, ma non provano conformità WCAG. Integra le scansioni axe con tastiera, screen reader e verifiche manuali di messaggi e contrasto. [12]
Per screenshot Playwright stabilizza dati, font, viewport e versione del browser. Esamina ogni modifica alla baseline. Un test visivo rileva un pulsante spostato, ma non sostituisce la verifica del comportamento. [13]
Test instabili e determinismo
Un test instabile cambia esito senza una variazione rilevante del comportamento. Le cause includono dati condivisi, race asincrone, orologi non controllati e servizi esterni. Ogni test crea i propri dati e pulisce lo stato. [9][14]
I tentativi aggiuntivi aiutano la diagnosi ma non eliminano la causa. Conserva tracce ed errori della console e riproduci con lo stesso seed e condizioni. Non normalizzare l’instabilità dei flussi critici.
Copertura e CI
La copertura misura esecuzione di istruzioni, funzioni, righe e rami, non qualità delle asserzioni. Neppure il 100% garantisce correttezza se il risultato non viene verificato. Definisci soglie in base al rischio e analizza i rami scoperti. [15]
In CI esegui npm ci, controllo tipi, test, copertura, build ed E2E con una versione Node controllata. Conserva report e tracce in caso di errore; amplia la matrice browser secondo il prodotto. L’esempio copre solo Chromium, non Firefox o WebKit. [16]
Matrice di regressione e manutenzione
Quantità: minimo, massimo, zero, testo e frazione; UI: errore, correzione e focus; API: successo, 503, tipo errato, indisponibilità e annullamento; acquisto reale: autorizzazione, nuovo tentativo e persistenza. Non tutto deve essere E2E. [1]
Quando trovi un bug, scrivi un test che fallisce prima della correzione e passa dopo. In revisione valuta significato delle asserzioni, stato condiviso e indipendenza dall’ordine. Elimina duplicati privi di protezione aggiuntiva.
