Test a React Capstone with Vitest and Testing Library
Introduction
This is lesson 4 of chapter 8, the last lesson of the capstone (domain capstone). The Harbor Workshops application now has a catalog, a URL-based filter, a detail page, and a booking workflow. Use tests and a browser walkthrough to show that the booking flow meets its criteria. Package the evidence so a reviewer can reproduce it.
Write automated tests with Vitest and React Testing Library, check accessibility and performance, and prepare a README and a short demo. Meta's official capstone includes self and peer review of the Little Lemon project. This chapter gives you a separate practice review for Harbor Workshops. Official capstone assessment (opens in a new tab)
Learning objectives
By the end of this lesson you can:
- Choose what to test using the test pyramid and the acceptance criteria.
- Write unit tests for pure functions (
validateBooking,seatsLeftFor, formatters). - Write component and integration tests with React Testing Library that mimic user behavior.
- Render routed components in a test with a memory router and the providers they need.
- Query elements by accessible role and name, and use
userEventcorrectly. - Run an accessibility self-review with keyboard testing, automated checks, and a manual checklist.
- Review performance and code quality, and refactor safely with tests as a net.
- Prepare a README, a demo script, and a self-assessment against the acceptance criteria.
1. What to test: the test pyramid, applied
Not every line deserves a test. Spend effort where bugs are likely and expensive.
| Layer | What it checks | Speed | Harbor Workshops examples |
|---|---|---|---|
| Unit | One function in isolation | Very fast | validateBooking, seatsLeftFor, formatPrice |
| Component / integration | A component or a few together, via the DOM | Fast | Level filter changes the list; booking form shows errors |
| End-to-end | The whole app in a real browser | Slower | Browse, book, confirm (optional for a capstone) |
Choose the layer that can catch the failure. Pure input rules are quick to test in isolation. Routing, shared state, and submission are best checked together. A browser walkthrough covers real keyboard behavior and layout. Derive the tests from your acceptance criteria (lesson 1): each criterion should be covered by at least one test or a documented manual check.
Test setup
Use Vitest for this Vite practice project. The React Testing Library queries and interactions carry over to the Jest examples from chapter 6. Review user-centered tests with React Testing Library for the testing approach.
npm install -D vitest jsdom @testing-library/dom @testing-library/react @testing-library/user-event @testing-library/jest-dom
npm pkg set "scripts.test=vitest run"Keep the React plugin in the Vite configuration and add the test settings. Use Node.js 24 as in lesson 2.
// vite.config.js
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./src/test/setup.js'],
},
});// src/test/setup.js
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(() => {
cleanup();
sessionStorage.removeItem('harbor.demo-bookings.v1');
});Run npm test in the practice project. Vitest transforms the JSX through the Vite configuration, and jsdom supplies DOM APIs for these tests. Use a browser for layout, actual focus styling, and accessibility announcements. Vitest guide (opens in a new tab) · Testing Library setup (opens in a new tab) · jest-dom Vitest integration (opens in a new tab)
2. Unit tests for pure functions
Pure functions are the cheapest tests to write and the most reliable.
// src/lib/validateBooking.test.js
import { expect, describe, test } from 'vitest';
import { validateBooking } from './validateBooking';
const valid = { name: 'Sam Rivera', email: 'sam@example.com', seats: '2' };
describe('validateBooking', () => {
test('accepts valid values', () => {
expect(validateBooking(valid, 5)).toEqual({});
});
test('requires a name that is not only spaces', () => {
expect(validateBooking({ ...valid, name: ' ' }, 5).name).toMatch(/enter your name/i);
});
test.each(['sam', 'sam@', 'sam@example', 'sam @example.com'])(
'rejects the email %s',
(email) => {
expect(validateBooking({ ...valid, email }, 5).email).toBeDefined();
},
);
test('rejects seats above availability (boundary)', () => {
expect(validateBooking({ ...valid, seats: '5' }, 5)).toEqual({});
expect(validateBooking({ ...valid, seats: '6' }, 5).seats).toMatch(/only 5/i);
});
test('rejects zero, negative, and fractional seats', () => {
for (const seats of ['0', '-1', '1.5', '']) {
expect(validateBooking({ ...valid, seats }, 5).seats).toBeDefined();
}
});
});Good habits visible here: boundary tests (exactly at the limit and just above), test.each for variations, and assertions about the message intent using a regular expression so that small wording changes do not break the test.
// src/lib/seats.test.js
import { expect, test } from 'vitest';
import { seatsLeftFor } from './seats';
const workshop = { id: 'w-1', capacity: 10, seatsTaken: 7 };
test('subtracts bookings of the same workshop only', () => {
const bookings = [
{ workshopId: 'w-1', seats: 2 },
{ workshopId: 'w-2', seats: 5 },
];
expect(seatsLeftFor(workshop, bookings)).toBe(1);
});
test('never returns a negative number', () => {
expect(seatsLeftFor(workshop, [{ workshopId: 'w-1', seats: 9 }])).toBe(0);
});3. Component tests the way users behave
React Testing Library's guiding principle is: the more your tests resemble the way your software is used, the more confidence they give. So you query by what a user perceives, such as role, label, and text, not by class names or component internals.
Query priority
| Priority | Query | Use for |
|---|---|---|
| 1 | getByRole('button', { name: /confirm booking/i }) |
Anything with an accessible role |
| 2 | getByLabelText(/email/i) |
Form fields |
| 3 | getByText(...) |
Non-interactive text |
| Last resort | getByTestId |
Cases where nothing semantic exists |
Using roles has a bonus: if the query fails because a button is really a div, you have found an accessibility bug.
Variants matter:
getBy...throws if not found: use for things that must be present.queryBy...returnsnullwhen no element matches: use to assert absence (expect(queryByText(...)).not.toBeInTheDocument()).findBy...returns a promise and waits: use for asynchronous results.
Testing the form
// src/components/BookingForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test, vi } from 'vitest';
import BookingForm from './BookingForm.jsx';
function setup(props = {}) {
const onSubmit = vi.fn();
const user = userEvent.setup();
render(<BookingForm seatsLeft={4} onSubmit={onSubmit} submitting={false} {...props} />);
return { onSubmit, user };
}
test('shows errors and does not submit an empty form', async () => {
const { onSubmit, user } = setup();
await user.click(screen.getByRole('button', { name: /confirm booking/i }));
expect(screen.getByLabelText(/full name/i)).toHaveAttribute('aria-invalid', 'true');
expect(screen.getByText(/enter your name/i)).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
expect(screen.getByLabelText(/full name/i)).toHaveFocus();
});
test('submits trimmed values as numbers', async () => {
const { onSubmit, user } = setup();
await user.type(screen.getByLabelText(/full name/i), ' Sam Rivera ');
await user.type(screen.getByLabelText(/email/i), 'sam@example.com');
await user.clear(screen.getByLabelText(/seats/i));
await user.type(screen.getByLabelText(/seats/i), '2');
await user.click(screen.getByRole('button', { name: /confirm booking/i }));
expect(onSubmit).toHaveBeenCalledWith({
name: 'Sam Rivera',
email: 'sam@example.com',
seats: 2,
});
});
test('disables the button while submitting', () => {
setup({ submitting: true });
expect(screen.getByRole('button', { name: /booking/i })).toBeDisabled();
});Notes: userEvent simulates a real sequence of events (focus, keydown, input, keyup) and is preferred over fireEvent. Its methods return promises, so await them. Create the user with userEvent.setup() before rendering. The first test also verifies focus management, which is a real requirement from lesson 3.
Testing routed screens with providers
Render the real App inside MemoryRouter. App already provides the booking context, so each render gets a fresh provider. The setup file clears the demo storage after each test.
// src/test/renderApp.jsx
import { render } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import App from '../App.jsx';
export function renderApp(route = '/') {
return render(
<MemoryRouter initialEntries={[route]}>
<App />
</MemoryRouter>,
);
}MemoryRouter keeps the history in memory. Set initialEntries to exercise the same paths used by the browser app.
// src/App.test.jsx
import { screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import { renderApp } from './test/renderApp.jsx';
test('filters the catalog by level from the URL', () => {
renderApp('/workshops?level=beginner');
const main = within(screen.getByRole('main'));
const catalog = within(main.getByRole('list'));
expect(screen.getByRole('status')).toHaveTextContent('1 workshop shown');
expect(catalog.getByRole('link', { name: 'Beginner Pottery' })).toBeInTheDocument();
expect(catalog.queryByRole('link', { name: 'Advanced Bike Repair' })).not.toBeInTheDocument();
});
test('shows a not-found page for an unknown workshop', () => {
renderApp('/workshops/does-not-exist');
expect(screen.getByRole('heading', { name: 'Page not found' })).toBeInTheDocument();
expect(screen.getByText(/could not find that workshop/i)).toBeInTheDocument();
});
test('reserves the last pottery seats and updates the catalog and detail', async () => {
const user = userEvent.setup();
renderApp('/workshops/w-101/book');
await user.type(screen.getByLabelText(/full name/i), 'Sam Rivera');
await user.type(screen.getByLabelText(/email/i), 'sam@example.com');
const seats = screen.getByRole('spinbutton', { name: 'Seats' });
await user.clear(seats);
await user.type(seats, '3');
await user.click(screen.getByRole('button', { name: /confirm booking/i }));
expect(await screen.findByRole('heading', { name: /demo booking confirmed/i })).toBeInTheDocument();
expect(screen.getByText('$135.00')).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'Back to workshops' }));
const card = within(await screen.findByRole('article', { name: 'Beginner Pottery' }));
expect(card.getByText('Fully booked')).toBeInTheDocument();
await user.click(card.getByRole('link', { name: 'Beginner Pottery' }));
expect(await screen.findByText('This workshop is fully booked.')).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Book seats' })).not.toBeInTheDocument();
});The filter test scopes its assertion to the results list so it can distinguish the absent Advanced Bike Repair card from the visible Advanced filter. The final test crosses the form, the async service, the reducer, and routing. findByRole waits for confirmation after the mock delay. The subsequent checks catch a regression where one view still reads only the fixture count. If your environment lacks crypto.randomUUID, use a supported runtime and check the jsdom version or inject a deterministic id at the service boundary in a test.
What not to test
- Implementation details (a state variable's name, the number of renders).
- Library behavior (that
useStateworks, that the router matches a path). - Styling, except where it carries meaning (use visual review for that).
If a refactor that keeps behavior forces you to rewrite many tests, the tests were too coupled to implementation.
4. Accessibility self-review
Test the catalog, the invalid form, the pending and failure states, and the confirmation. Use the chapter 7 lesson on WCAG 2.2 checks and usability testing to distinguish accessibility checks from broader usability findings.
- Keyboard walkthrough. Check the skip link, filter buttons, form submission, and Back navigation. Focus should remain on the filter when the query changes, move to the first invalid field after its message renders, and reach the main content after navigation.
- Automated browser scan. Run axe or the browser's Lighthouse accessibility audit on representative states. Investigate each finding and rerun the scan after repairs.
- Manual review. Check the criteria below at narrow and wide sizes and try a screen reader. Record the browser, assistive technology, route, and state for each result.
| Check | What to verify |
|---|---|
| Contrast | Normal text meets 4.5:1 and large text meets 3:1 under WCAG AA where applicable. Required visual cues for controls and meaningful graphics generally need 3:1 against adjacent colors. |
| Text resize and reflow | Resize text to 200% without losing content or function. Separately check the vertically scrolling page at a width equivalent to 320 CSS pixels for reflow. Content that needs two dimensions can qualify for an exception. |
| Images | Informative images have an equivalent text alternative. Decorative images use alt="". |
| Headings | Each view has a clear main heading and a logical heading hierarchy. |
| Forms | Each field has a visible label and errors identify what to correct. The relevant descriptions are exposed when the fields receive focus. |
| Status | A filter result change, submission error, and successful navigation are perceivable. Verify announcements during use. |
| Motion | Check motion preferences if you add animation. |
| Target size | Check both target dimensions against 24 by 24 CSS pixels for WCAG 2.2 AA where applicable. Review exceptions such as sufficient spacing and inline links. |
A browser scan covers the rules it can evaluate for the current state. DOM tests cannot judge reflow, keyboard order across an entire journey, or how all assistive technologies announce changes. axe-core has limited jsdom support, including for color contrast. WCAG 2.2 (opens in a new tab) · axe-core support (opens in a new tab)
5. Performance and code-quality review
Performance
- Measure first. Build the practice app with
npm run buildand usenpm run previewto inspect that build locally. Run Lighthouse against the preview and record the URL and conditions. Check the deployed app separately for asset loading and route fallback. - Bundle size. Check what the build reports. Split rarely visited routes with
React.lazyandSuspenseonly when the bundle or an audit warrants it. - Images. Set
widthandheight(or an aspect ratio) to avoid layout shift, serve appropriately sized images, and useloading="lazy"for below-the-fold images. - Re-renders. Use the React DevTools Profiler to identify expensive interactions. Consider memoization or virtualization when the measurements indicate a problem.
- Core Web Vitals. Track Largest Contentful Paint, Interaction to Next Paint, and Cumulative Layout Shift. A local Lighthouse audit provides lab measurements. Evaluate real-user INP with field data where available. Web Vitals (opens in a new tab)
Code quality
Run ESLint and fix the warnings. Then review your own diff the way a colleague would, with questions such as:
- Is there duplicated markup that should be a component?
- Are names intention-revealing (
seatsLeftFor, notcalc2)? - Is derived data computed rather than stored?
- Are effects necessary, and do they clean up?
- Are all props used, and are the error states handled?
- Are secrets or API keys committed? (Never commit them.)
- Is dead code or commented-out code removed?
Refactor in small steps with the tests green after each one. Tests are the safety net that makes cleanup low-risk.
6. Package and present the work
README structure
- Title and one-sentence pitch.
- Screenshot or short screen recording of the main flow.
- Features mapped to the user stories.
- Tech stack and why.
- How to run (
npm ci,npm run devwith the committed lockfile), how to test (npm test), and how to build. - Decisions and trade-offs: URL for filters, integer cents, tab-scoped demo storage and simulated availability.
- Accessibility and performance notes with the audit results.
- Known limitations and next steps.
- Credits and licenses for fonts and images.
Git history
A reviewer reads the history to see how you work. Use meaningful commit messages in the imperative ("Add booking form validation"), keep commits focused, and do not commit node_modules or build output (.gitignore). Tag a release (v1.0.0) when the acceptance criteria pass.
The five-minute demo
Prepare a script: (1) the problem and user, 30 seconds; (2) the main flow live, 2 minutes: browse, filter, detail, book with an error, fix it, confirm; (3) one technical decision you are proud of, 1 minute; (4) test and accessibility results, 1 minute; (5) what you would do next, 30 seconds. Rehearse, and prepare for questions like "why a reducer here?" or "what breaks if the network fails?".
Self-assessment against criteria
Create a table with each acceptance criterion, its evidence (test name, manual check), and its status. Be honest. Name the limits of your evidence and show how a reviewer can reproduce each result.
Worked example: trace a stale seat count
Problem. A developer connects the booking form to the reducer and leaves the catalog card on its fixture-only calculation. After booking all three pottery seats, the confirmation appears and the catalog still offers the workshop as available.
Step 1: reproduce the sequence. Use the booking integration test above. Check which assertions pass and which view reports the wrong count.
Step 2: inspect the data paths. Compare the card and detail imports with the booking page. seatsLeft(workshop) reads the fixture only. seatsLeftFor(workshop, bookings) subtracts the tab's bookings.
Step 3: fix both readers. Use the useSeatsLeft hook from lesson 3 in the card and detail views. Keep seatsLeftFor as the calculation shared by the hook and the booking page. Remove the fixture-only helper once its readers are migrated.
Step 4: preserve the observable check. Confirm that the catalog shows Fully booked, the detail omits Book seats, and refreshing the tab preserves availability when storage is available. A passing confirmation assertion by itself covers only part of the journey.
Common pitfalls and study tips
- Testing implementation details. Prefer queries by role, label, and text.
- Forgetting
awaitonuserEventcalls. The assertion runs before the interaction finishes. - Using
getByto assert absence. It throws; usequeryByfor "not present". - Shared state between tests. Clean up each rendered app and remove its demo session record between tests.
- Snapshot tests everywhere. Large snapshots are approved without being read; use targeted assertions.
- Mocking too much. Replace slow or nondeterministic boundaries when useful. Keep the form, reducer, routes, and visible assertions in the integration test.
- Relying on automated accessibility checks alone.
- Auditing the dev server. Measure a production build.
- A README with no run instructions. The reviewer cannot evaluate what they cannot start.
Study tip. Choose a role and accessible name when available. Use findBy for an asynchronous appearance and queryBy for absence. Await userEvent when exercising a user interaction.
Mini case study: reviewing a classmate's capstone
You receive a classmate's to-do list capstone to review. You find: no README; tests that select elements with container.querySelector('.btn-3'); a clicked div acting as a button; images without alt; a 4 MB hero image; and console.log statements left in the code.
Task. Write the review feedback as prioritized, constructive items.
Solution.
- High: no README. A reviewer cannot run the project. Add what it is, how to run it, how to test it, and a screenshot.
- High: a
divused as a button. It is not focusable or operable by keyboard. Replace it with<button type="button">, which also gives the Enter and Space behavior for free. - High: missing
alttext. Add meaningful alternatives, oralt=""for decorative images. - Medium: a 4 MB hero image. Its transfer size can delay Largest Contentful Paint if it is the main visible image. Check which element Lighthouse reports before prioritizing the fix. Resize it, compress it, use a modern format, and set dimensions.
- Medium: tests tied to class names. They break with any styling change. Query by role and accessible name, which exercises the semantics the tests depend on.
- Low: leftover
console.log. Remove debugging output.
Each item states the problem, the user impact, and the fix, and they are ordered by impact. Good feedback is specific and kind.
Key terms
- Test pyramid: many unit tests, fewer integration tests, few end-to-end tests.
- React Testing Library: a library that tests components through the DOM the way users use them.
userEvent: simulates realistic user interactions.MemoryRouter: a router keeping history in memory, for tests.- Integration test: a test crossing several units.
- axe: an automated accessibility rules engine.
- Core Web Vitals: user-centered performance metrics (LCP, INP, CLS).
- Acceptance criteria: verifiable conditions that define a story as done.
Summary checklist
- Pure functions have unit tests, including boundaries.
- The form, filter, and booking journey have user-centered tests.
- Tests query by role and label, and
awaituserEvent. - A keyboard-only run, an automated scan, and the manual checklist are complete.
- A production build was audited, and issues were fixed.
- Lint is clean, and dead code and secrets are removed.
- The README, screenshot, run, test, and decision notes exist.
- A self-assessment maps each acceptance criterion to evidence.
- The five-minute demo is rehearsed.
Sources and further reading
- Testing Library, guiding principles and queries: https://testing-library.com/docs/queries/about (opens in a new tab)
- Testing Library, user-event: https://testing-library.com/docs/user-event/intro (opens in a new tab)
- Jest documentation: https://jestjs.io/docs/getting-started (opens in a new tab)
- Vitest documentation: https://vitest.dev/guide/ (opens in a new tab)
- web.dev, Core Web Vitals: https://web.dev/articles/vitals (opens in a new tab)
- Deque axe-core browser and jsdom support (opens in a new tab)
- React Router MemoryRouter (opens in a new tab)
- Vitest test environments (opens in a new tab)
- WCAG 2.2: https://www.w3.org/TR/WCAG22/ (opens in a new tab)
- Meta Front-End Developer Professional Certificate (Coursera): https://www.coursera.org/professional-certificates/meta-front-end-developer (opens in a new tab)
