Frontend testing
Good frontend tests check what the user sees and does, not how the code is built inside. Write many fast component and integration tests with Vitest and Testing Library, mock the network with MSW, and keep a few end-to-end tests with Playwright for the most important flows, like checkout. Never wait with fixed sleeps; wait for the thing you expect.
Author: bezzad
Contents
The problem: tests that break for the wrong reasons
Our online shop has 600 frontend tests. Still, last month a bug reached production: the “Place order” button stayed disabled for some users. No test failed. At the same time, the team hates the tests:
- A small refactor breaks 40 tests. The tests checked the inner state of components and the names of private functions. The app still worked.
- The real bug was not caught. Every test mocked the fetch function, and the mocks did not match the real API anymore.
- The CI is red every other day for no clear reason. Someone added sleep calls “to make it stable”.
The tests were testing the wrong things in the wrong way. Let us fix that.
What kind of tests, and how many
There are two common pictures for this. The classic test pyramid says: many unit tests, fewer integration tests, very few end-to-end (E2E) tests. For frontend apps, many teams use the testing trophy instead. It puts the most weight on integration tests: a component tested together with its children, the way a user uses it.
- Static checks. TypeScript in strict mode and a linter. They find many bugs before any test runs.
- Unit tests for pure logic: price calculation, discount rules, input validation. Fast and simple.
- Component and integration tests for most of the UI: the cart, the search box, the checkout form. They run in Node with a fake DOM, so they are fast, but they test real behavior.
- End-to-end tests for a few critical flows, in a real browser against the real app. They give the most confidence but are slow and harder to keep stable.
The rule behind it: the more your tests look like the way the software is used, the more confidence they give you.
Unit tests for pure logic with Vitest
Vitest is a fast test runner that works well with Vite projects. It uses the familiar describe, it and expect functions.
// cart-total.ts
export type CartLine = { priceCents: number; quantity: number };
export function cartTotalCents(lines: CartLine[], discountPercent = 0): number {
const subtotal = lines.reduce((sum, l) => sum + l.priceCents * l.quantity, 0);
return Math.round(subtotal * (1 - discountPercent / 100));
}
// cart-total.test.ts
import { describe, it, expect } from 'vitest';
import { cartTotalCents } from './cart-total';
describe('cartTotalCents', () => {
it('adds up price times quantity', () => {
expect(cartTotalCents([{ priceCents: 1250, quantity: 2 }])).toBe(2500);
});
it('applies a percent discount', () => {
expect(cartTotalCents([{ priceCents: 1000, quantity: 1 }], 10)).toBe(900);
});
it('returns 0 for an empty cart', () => {
expect(cartTotalCents([])).toBe(0);
});
});
- Keep logic out of components when you can. A pure function is the easiest thing to test.
- Use cents, not floating-point dollars. It avoids rounding bugs like 0.1 plus 0.2.
Component tests with Testing Library
Testing Library has one main idea: find elements the way a user finds them. A user does not know your CSS classes or component state. They see a button named “Add to cart”, or a text field labeled “Email”.
This example uses no framework. It is a plain TypeScript component and the DOM version of Testing Library. The React, Vue and Angular versions of Testing Library have the same queries.
// add-to-cart.ts
export function renderAddToCart(
root: HTMLElement,
addToCart: (productId: string) => Promise<void>,
): void {
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Add to cart';
const status = document.createElement('p');
status.setAttribute('role', 'status');
root.append(button, status);
button.addEventListener('click', async () => {
button.disabled = true;
await addToCart('p42');
status.textContent = 'Added to cart';
button.disabled = false;
});
}
// @vitest-environment jsdom
// add-to-cart.test.ts
import { it, expect, vi, afterEach } from 'vitest';
import { screen } from '@testing-library/dom';
import userEvent from '@testing-library/user-event';
import { renderAddToCart } from './add-to-cart';
afterEach(() => document.body.replaceChildren());
it('shows a message after adding to the cart', async () => {
const addToCart = vi.fn(async (_id: string) => {});
renderAddToCart(document.body, addToCart);
const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: 'Add to cart' }));
expect(addToCart).toHaveBeenCalledWith('p42');
expect(await screen.findByText('Added to cart')).toBeTruthy();
});
- Query by role and accessible name first (the getByRole query). Then by label (getByLabelText) for form fields. If a test cannot find a button by its role, a screen reader user probably cannot either.
- Use a test id only when there is no role, label or text to find the element. It is the last choice.
- Use user-event, not raw events. A user-event click also sends pointer and focus events, like a real user.
- Do not test implementation details: inner state, private functions, CSS class names, how many times a component rendered. Test what appears on the screen.
Tests the implementation
- Finds the button by the class name add-btn
- Checks that the component state isLoading is true
- Breaks when you rename a class, even if the page works
Tests what the user sees
- Finds the button by role and the name “Add to cart”
- Checks that the button is disabled and that the message appears
- Breaks only when the user would notice a change
Mock the network with MSW
Mocking the fetch function in every test has two problems. Each test repeats the same setup. And the mock knows nothing about the real request: wrong URL, wrong method or wrong body still pass.
MSW (Mock Service Worker) catches requests at the network level. Your code calls fetch exactly as in production. MSW answers with the data you define. In the browser it uses a Service Worker; in Node tests it hooks into the request modules.
// test/server.ts
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
export const server = setupServer(
http.get('https://api.shop.example/products', () =>
HttpResponse.json([{ id: 'p42', name: 'Blue mug', priceCents: 1250 }]),
),
);
// test/setup.ts (listed in setupFiles in the Vitest config)
import { beforeAll, afterEach, afterAll } from 'vitest';
import { server } from './server';
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
To test an error, change the handler only for one test:
server.use(
http.get('https://api.shop.example/products', () =>
new HttpResponse(null, { status: 500 }),
),
);
- The onUnhandledRequest option set to error makes a test fail when the code calls an endpoint you did not mock. You see the mistake at once.
- The resetHandlers call after each test removes one-test overrides, so tests do not affect each other.
Async UI: wait for the result, not for time
Most UI updates are async: data arrives, a message appears. A fixed sleep is either too short (the test fails on a slow CI machine) or too long (every run is slow).
- The findBy queries wait for the element. They check again and again until it appears, or fail after a timeout (one second by default).
- The getBy queries check once and throw if the element is not there. Use them for things that are already on the screen.
- The queryBy queries return null instead of throwing. Use them to check that something is not there.
End-to-end tests with Playwright
An E2E test opens a real browser, uses the real app and checks the result. Playwright supports Chromium, Firefox and WebKit. Here is the most important flow of our shop:
// checkout.spec.ts
import { test, expect } from '@playwright/test';
test('a guest can buy a product', async ({ page }) => {
await page.goto('/'); // baseURL is set in playwright.config.ts
await page.getByRole('searchbox', { name: 'Search products' }).fill('mug');
await page.getByRole('link', { name: 'Blue mug' }).click();
await page.getByRole('button', { name: 'Add to cart' }).click();
await page.getByRole('link', { name: 'Cart' }).click();
await page.getByRole('button', { name: 'Checkout' }).click();
await page.getByLabel('Email').fill('sara@example.com');
await page.getByLabel('Address').fill('12 Main Street');
await page.getByRole('button', { name: 'Place order' }).click();
await expect(page.getByRole('heading', { name: 'Thank you for your order' })).toBeVisible();
});
- Actions wait automatically. Before a click, Playwright waits until the element is visible, stable, enabled and able to receive the click.
- Use web-first assertions. An expect with await and a locator, like toBeVisible or toHaveText, retries until the condition is true or the timeout ends.
- Do not use the waitForTimeout method. It is a fixed sleep. Wait for an element, a URL or a response instead.
// Bad: checks once, no retry
expect(await page.getByText('Added to cart').isVisible()).toBe(true);
// Good: retries until visible
await expect(page.getByText('Added to cart')).toBeVisible();
Flaky tests
A flaky test sometimes passes and sometimes fails with the same code. It teaches the team to ignore red builds, which is worse than having no test.
| Cause | Fix |
|---|---|
| Fixed sleeps and timing guesses | Wait for a condition: findBy queries, web-first assertions |
| Tests that share data or depend on order | Each test creates its own data and cleans up |
| Real third-party services (payment, maps) | Mock them, or use their test mode |
| The current date, time zone or random values | Use fake timers and a fixed seed or a fixed date |
| Animations | Wait for the end state, or turn animations off in tests |
| Too many E2E tests for small details | Move those checks down to component tests |
Playwright can retry failed tests and record a trace on the first retry. The trace shows each step, the DOM and the network, so you can see why it failed. A retry helps you find flaky tests; it is not the fix.
What to test in the checkout
The checkout is where the money is. A good mix for our shop:
- Unit tests: total price, discount codes, shipping cost per country, validation of the postal code.
- Component tests with MSW: the form shows an error for an empty email; the “Place order” button is disabled while the order is sending; a server error shows a clear message and keeps the form data; an out-of-stock product shows a warning.
- One or two E2E tests: a guest buys one product from search to the thank-you page; maybe a logged-in user with a saved address. Use the payment provider’s test mode, never real payments.
Accessibility checks in tests
- Role and label queries are already a small accessibility check. A button without a name, or an input without a label, is hard to find.
- Add an automated scan, for example axe with Playwright:
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('checkout page has no detectable accessibility issues', async ({ page }) => {
await page.goto('/checkout');
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations).toEqual([]);
});
- Test the keyboard too: can a user reach “Place order” with the Tab key and press it with Enter?
- Automated tools find only part of the problems. A manual check with a keyboard and a screen reader is still needed.
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| Testing inner state and private functions | Tests break on every refactor | Test what the user sees and does |
| Finding elements by CSS class or test id | Tests are fragile and miss accessibility bugs | Query by role, label and text |
| Mocking fetch in every test | Mocks drift away from the real API | Mock the network once with MSW |
| Fixed sleeps | Slow and flaky tests | findBy queries and web-first assertions |
| Hundreds of E2E tests | Slow, flaky CI | E2E only for critical flows |
| Tests that depend on each other | Fail when run in another order | Each test sets up and cleans up its own data |
| Retries hide flaky tests | Real bugs get ignored | Use the trace to find and fix the cause |
Summary in seven lines
- Put most effort into component and integration tests. Use unit tests for pure logic and a few E2E tests for critical flows.
- Test what the user sees: query by role and label, click with user-event, avoid implementation details.
- Use a test id only when no role, label or text can find the element.
- Mock the network once with MSW instead of mocking fetch in every test.
- Never sleep for a fixed time. Use findBy queries and Playwright web-first assertions.
- Flaky tests come from timing, shared data and real outside services. Find the cause; retries are not a fix.
- In checkout, test prices, validation, errors and one full purchase, and add an automated accessibility scan.