Choose the right test boundary
Test the quantity rule from 1 to 10 in isolation without a DOM. Check the form, feedback and recovery with a component test; exercise the HTTP client against a response contract in an integration test. Reserve end-to-end tests for workflows where real layers must cooperate. [1][2]
There is no universal test-pyramid ratio. Invest where regressions are costly and a lower layer cannot detect the failure. One browser test of the form does not prove that an order is persisted; this sample only saves presentation state.
Unit tests: contracts and boundaries
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 accepts a nonempty string of ASCII digits and returns an integer from 1 to 10; leading zeros are allowed. Fractions, exponential notation, whitespace and out-of-range values are rejected. Table-driven cases cover both bounds and invalid inputs. [1]
Do not assert how often a regular expression runs. Assert the result or error type. A refactoring that preserves the public contract should not break the test.
Given–When–Then (GWT) and 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 describes the initial context, When the action or event, and Then the expected observable outcome. The stock integration test first configures the API response, calls the adapter and checks the result. [20]
GWT is an optional way to organize tests, not a Vitest or Playwright requirement. AAA (Arrange, Act, Assert) is equally natural for unit tests. For richer acceptance scenarios, Gherkin and Cucumber are options; a scenario alone is not an executable test without matching step definitions. Do not add mechanical comments to obvious short tests. [20][21]
Tooling and project configuration
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"],
},
},
});
Related tool comparisons on POLPROG: Jest vs Vitest.
Vitest fits Vite projects; Jest remains reasonable in existing projects with custom transforms and test suites. A test runner does not replace TypeScript compilation. Run tsc separately. [3][4] [18]
The example uses Vitest 4, Vite 7 and MSW 2 syntax without claiming these are the latest releases. Install dependencies, commit the lockfile and use npm ci in CI. The configuration separates Vitest tests from e2e; jsdom is selected only for the DOM test.
Component tests: observable behavior
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="/en/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",
);
});
The form has a label, a button, status feedback and aria-invalid. We avoid private properties and CSS classes. Testing Library finds elements by role and name, and user-event models interactions. Use getBy for immediate presence, queryBy for absence and findBy to await an element. [5][6]
The test exercises failure and recovery, focus and removal of aria-invalid. The component returns a cleanup function; after each test we remove listeners and DOM. jsdom does not reproduce a full browser layout or rendering engine. [19]
Integration: controlled HTTP responses
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 checks response.ok and validates unknown JSON. Fetch does not reject merely because a server returns 503. MSW intercepts at the network boundary instead of replacing the function under test; cover success, HTTP failure, invalid contracts and network errors. [7] [17]
In Node, setupServer rejects unhandled requests and extra handlers are reset after each test. A simulated API does not establish compatibility with the real service. Add contract tests or integration against a test backend; the adapter also accepts an abort signal.
Named predicates separate response structure checks from numeric value checks. Test the adapter contract, including a missing field, null, fractional and negative numbers, and integers outside the safe range.
Mocks, stubs, spies and time
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();
});
A stub supplies a controlled result; a spy records calls, often preserving original behavior; mock is a broader term for a dependency substitute, sometimes with expectations. Tool terminology varies. Replace boundaries, not the function whose correctness you are testing. [3][8]
For debounce, use vi.useFakeTimers, advance time explicitly and restore real timers afterward. Choose asynchronous timer methods when promises are involved. Do not combine fake timers with DOM waits blindly; avoid real sleeps and await asynchronous test operations.
The independent example below schedules and cancels a refresh; it is not a debounce implementation.
E2E: a real browser
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");
});
Related tool comparisons on POLPROG: Cypress vs Playwright.
Playwright opens the built app, finds the field by name and submits with the keyboard. Actions wait for relevant actionability conditions, while web assertions retry until their timeout. Do not replace these with arbitrary sleeps. [9][10]
The config launches a server at a defined address; build before E2E. Cypress also supports component and E2E testing. For a real ordering system, add a flow with a test backend and controlled data that verifies persistent writes and rejection of unauthorized requests. [2][11]
Accessibility and visual regression
Focus and semantic-role assertions catch useful regressions but cannot establish WCAG conformance. Supplement automated axe scans with keyboard, screen-reader and manual feedback and contrast checks. [12]
For Playwright screenshots, stabilize data, fonts, viewport and browser version. Review baseline changes instead of accepting them wholesale. A visual test catches a moved button but cannot replace a behavioral assertion. [13]
Flaky tests and determinism
A flaky test changes its result without a relevant change in tested behavior. Common causes include shared data, asynchronous races, uncontrolled clocks and external services. Each test should create its own data and clean up state. [9][14]
Retries provide diagnostic evidence but do not fix the cause. Save traces and console errors and reproduce with the same data seed and conditions. Do not normalize flakiness on critical paths.
Coverage and CI
Coverage measures execution of statements, functions, lines and branches, not assertion quality. Even 100% coverage cannot guarantee correctness: a test may execute code without checking the result. Set thresholds based on risk and inspect uncovered branches. [15]
In CI run npm ci, typecheck, tests, coverage, build and E2E on a controlled Node version. Retain reports and traces on failure and expand the browser matrix to match product requirements. The example covers Chromium only; it does not prove Firefox or WebKit compatibility. [16]
Regression matrix and maintenance
For quantity, cover minimum, maximum, zero, text and fractions; for UI, error, correction and focus; for API, success, 503, bad type, unavailability and cancellation; for real checkout, authorization, retries and persistence. Not all scenarios belong in E2E. [1]
When a bug is found, write a test that fails before the fix and passes afterward. In reviews, inspect assertion meaning, shared state and order independence. Remove duplicates if they provide no additional protection.
