Elegir el nivel adecuado
Comprueba la regla de cantidad de 1 a 10 de forma aislada, sin DOM. Una prueba de componente verifica formulario, mensajes y recuperación; una de integración comprueba el cliente HTTP frente al contrato de respuesta. Reserva E2E para flujos que requieren capas reales cooperando. [1][2]
No existe una proporción universal de pirámide. Invierte donde las regresiones sean costosas y no puedan detectarse en un nivel inferior. Una prueba de navegador del formulario no demuestra que se guarde un pedido; el ejemplo solo guarda estado de presentación.
Pruebas unitarias: contrato y límites
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 acepta una cadena no vacía de dígitos ASCII y devuelve un entero de 1 a 10; permite ceros iniciales. Rechaza fracciones, notación exponencial, espacios y valores fuera del rango. Los casos parametrizados cubren ambos límites y entradas inválidas. [1]
No compruebes cuántas veces se ejecuta una expresión regular, sino el resultado o tipo de error. Una refactorización que conserve el contrato no debe romper la prueba.
Given–When–Then (GWT) y 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 describe el contexto inicial, When la acción o el evento y Then el resultado observable esperado. La prueba de integración de existencias configura la respuesta de la API, llama al adaptador y comprueba el resultado. [20]
GWT es una estructura opcional, no un requisito de Vitest ni Playwright. AAA (Arrange, Act, Assert) también es natural en pruebas unitarias. Gherkin y Cucumber son opciones para escenarios de aceptación más elaborados; sin definiciones de pasos correspondientes, un escenario no es una prueba ejecutable. Evita comentarios mecánicos en pruebas cortas evidentes. [20][21]
Herramientas y configuración
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"],
},
},
});
Comparaciones de herramientas en POLPROG: Jest vs Vitest.
Vitest encaja con Vite; Jest sigue siendo razonable en proyectos existentes con transformaciones y suites propias. El ejecutor de pruebas no sustituye al compilador TypeScript. Ejecuta tsc por separado. [3][4] [18]
El ejemplo usa sintaxis de Vitest 4, Vite 7 y MSW 2 sin afirmar que sean las versiones más recientes. Instala dependencias, versiona el archivo de bloqueo y usa npm ci en CI. Separa las pruebas Vitest de e2e; jsdom solo se selecciona para la prueba DOM.
Pruebas de componentes: comportamiento observable
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="/es/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",
);
});
El formulario tiene etiqueta, botón, mensaje de estado y aria-invalid. Evita probar propiedades privadas o clases CSS. Testing Library busca por rol y nombre; user-event modela interacciones. getBy comprueba presencia inmediata, queryBy ausencia y findBy espera la aparición. [5][6]
La prueba cubre error, corrección, foco y retirada de aria-invalid. El componente devuelve una función de limpieza; tras cada prueba elimina listeners y DOM. jsdom no reproduce el motor de renderizado ni todo el diseño de un navegador real. [19]
Integración: respuestas HTTP controladas
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 comprueba response.ok y valida JSON desconocido. Fetch no rechaza una promesa solo por un estado 503. MSW intercepta la petición en la frontera de red sin sustituir la función probada; cubre éxito, fallo HTTP, contrato inválido y fallo de red. [7] [17]
En Node, setupServer rechaza peticiones sin manejador; reinicia los manejadores adicionales tras cada prueba. Una API simulada no demuestra compatibilidad con el servicio real. Añade pruebas de contrato o integración con un backend de pruebas; el adaptador acepta una señal de cancelación.
Los predicados con nombre separan la comprobación de la estructura de la respuesta de la validación numérica. Prueba el contrato del adaptador con campos ausentes, null, fracciones, números negativos y enteros fuera del rango seguro.
Mocks, stubs, spies y tiempo
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();
});
Un stub proporciona una respuesta controlada; un spy registra llamadas, a menudo conservando el comportamiento original; mock es un término más amplio para sustituciones de dependencias, a veces con expectativas. La terminología varía. Sustituye las fronteras, no la función probada. [3][8]
Para debounce usa vi.useFakeTimers, avanza el reloj explícitamente y restaura los temporizadores reales. Con promesas, selecciona variantes asíncronas cuando corresponda. No combines sin cuidado temporizadores falsos y esperas del DOM; evita pausas reales y espera las operaciones asíncronas.
El ejemplo independiente programa y cancela una actualización; no implementa debounce.
E2E: navegador real
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");
});
Comparaciones de herramientas en POLPROG: Cypress vs Playwright.
Playwright abre la aplicación compilada, localiza el campo por su nombre y envía mediante teclado. Las acciones esperan condiciones de interacción y las aserciones web reintentan hasta el límite de tiempo. No las sustituyas por pausas arbitrarias. [9][10]
La configuración inicia un servidor en una dirección definida; compila antes de E2E. Cypress también admite pruebas de componentes y E2E. Para pedidos reales, añade un flujo con backend de pruebas y datos controlados que compruebe persistencia y rechazo de peticiones no autorizadas. [2][11]
Accesibilidad y regresión visual
Las aserciones de foco y roles semánticos ayudan a detectar regresiones, pero no prueban conformidad WCAG. Complementa los análisis axe con teclado, lector de pantalla y revisión manual de mensajes y contraste. [12]
Estabiliza datos, fuentes, viewport y versión del navegador para capturas de Playwright. Revisa los cambios de referencia antes de aceptarlos. Una prueba visual detecta un botón desplazado, pero no sustituye las aserciones de comportamiento. [13]
Pruebas inestables y determinismo
Una prueba inestable cambia de resultado sin un cambio relevante de comportamiento. Las causas incluyen datos compartidos, carreras asíncronas, relojes no controlados y servicios externos. Cada prueba crea sus datos y limpia su estado. [9][14]
Los reintentos aportan información diagnóstica, no corrigen la causa. Conserva trazas y errores de consola y reproduce con la misma semilla y condiciones. No normalices la inestabilidad en flujos críticos.
Cobertura y CI
La cobertura mide ejecución de instrucciones, funciones, líneas y ramas, no calidad de aserciones. Ni el 100 % garantiza corrección si una prueba ejecuta código sin comprobar su resultado. Define umbrales por riesgo y revisa ramas no cubiertas. [15]
En CI ejecuta npm ci, comprobación de tipos, pruebas, cobertura, build y E2E con una versión controlada de Node. Conserva informes y trazas ante fallos; amplía la matriz según el producto. El ejemplo solo cubre Chromium, no Firefox ni WebKit. [16]
Matriz de regresión y mantenimiento
Cantidad: mínimo, máximo, cero, texto, fracciones; UI: error, corrección, foco; API: éxito, 503, tipo incorrecto, indisponibilidad y cancelación; compra real: autorización, reintentos y persistencia. No todo debe ser E2E. [1]
Ante un fallo, escribe una prueba que falle antes de corregirlo y pase después. En revisión comprueba el significado de las aserciones, el estado compartido y la independencia del orden. Elimina duplicados sin protección adicional.
