# Testing a React App the Practical Way: Vitest, React Testing Library, Playwright and Accessibility

Most React tutorials stop at "it renders." Real projects need confidence that things keep working, for every user, including those using a keyboard or a screen reader.

This post shows a small, opinionated testing setup on a **Vite + React + TypeScript** app. You'll get a mental model plus snippets you can reuse. It assumes you're comfortable with JavaScript, TypeScript and basic React.

The full project is in this [link](https://github.com/leeonscoding/react-week9). It runs on Windows and Linux with the same commands.

## The mental model

| Layer | Tool | What it answers |
| --- | --- | --- |
| Component / unit | Vitest + React Testing Library | "Does this component behave correctly for the user?" |
| End-to-end | Playwright | "Does the real app work in a real browser?" |
| Accessibility | RTL queries + axe-core | "Can everyone use it?" |

Write many fast component tests, a few end-to-end tests for critical flows, and let accessibility checks ride along in both.

## 1\. Setup

```bash
npm create vite@latest my-app -- --template react-ts
cd my-app
npm i -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
npm i -D @playwright/test @axe-core/playwright
```

Vitest reads your Vite config, so there's no separate Babel or transform setup:

```ts
// vite.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
    globals: true,
    setupFiles: './src/test-setup.ts',
    include: ['src/**/*.test.{ts,tsx}'], // keeps Playwright specs out of Vitest
  },
});
```

```ts
// src/test-setup.ts
import '@testing-library/jest-dom/vitest';
```

Add `"types": ["vitest/globals", "@testing-library/jest-dom"]` to `tsconfig.json` so `describe`, `it` and matchers like `toBeInTheDocument` type-check.

## 2\. The component under test

A small task list. Note the accessibility details: a real `<label>`, `aria-invalid`, an error linked with `aria-describedby`, and `role="alert"` / `role="status"` so screen readers announce changes.

```tsx
// src/Tasks.tsx (trimmed)
const errorId = useId();

<form onSubmit={handleSubmit} noValidate>
  <label htmlFor="new-task">New task</label>
  <input
    id="new-task"
    value={title}
    onChange={(e) => setTitle(e.target.value)}
    aria-invalid={Boolean(error)}
    aria-describedby={error ? errorId : undefined}
  />
  <button type="submit">Add task</button>
  {error && <p id={errorId} role="alert">{error}</p>}
</form>

<p role="status">{remaining} {remaining === 1 ? 'task' : 'tasks'} left</p>
```

## 3\. Vitest + React Testing Library

RTL's philosophy: **test what the user sees, not implementation details.** Query by role and label, the way assistive technology does, instead of by class names or test IDs.

```tsx
// src/Tasks.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Tasks } from './Tasks';

it('adds a task and clears the input', async () => {
  const user = userEvent.setup();
  render(<Tasks />);

  await user.type(screen.getByLabelText(/new task/i), 'Write blog');
  await user.click(screen.getByRole('button', { name: /add task/i }));

  expect(screen.getByRole('checkbox', { name: 'Write blog' })).toBeInTheDocument();
  expect(screen.getByLabelText(/new task/i)).toHaveValue('');
});

it('shows an accessible error when the title is empty', async () => {
  const user = userEvent.setup();
  render(<Tasks />);

  await user.click(screen.getByRole('button', { name: /add task/i }));

  expect(screen.getByRole('alert')).toHaveTextContent('Task title is required');
  expect(screen.getByLabelText(/new task/i)).toBeInvalid();
});
```

Habits worth keeping:

- **Prefer** `getByRole`, then `getByLabelText`, then `getByText`. Use `getByTestId` only as a last resort. If `getByRole` can't find your element, that's often an accessibility bug.
- **Use** `userEvent`**, not** `fireEvent`**.** It simulates real interaction (focus, typing, clicks).
- `getBy*` **throws if missing,** `queryBy*` **returns** `null` (use it to assert absence), and `findBy*` **waits** for async UI.
- Don't assert on state or internals. Assert on what the DOM shows.

Run it with `npm test` (watch mode) or `npm run test:run` (CI).

## 4\. Playwright for end-to-end tests

Component tests run in jsdom, which is not a real browser. Playwright runs your app in actual Chromium, Firefox or WebKit. Let it start the dev server for you:

```ts
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './e2e',
  use: { baseURL: 'http://localhost:5173' },
  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
  webServer: {
    command: 'npm run dev',
    url: 'http://localhost:5173',
    reuseExistingServer: !process.env.CI,
  },
});
```

```ts
// e2e/tasks.spec.ts
import { test, expect } from '@playwright/test';

test('user can add and complete a task', async ({ page }) => {
  await page.goto('/');

  await page.getByLabel('New task').fill('Ship the blog');
  await page.getByRole('button', { name: 'Add task' }).click();

  const checkbox = page.getByRole('checkbox', { name: 'Ship the blog' });
  await checkbox.check();

  await expect(page.getByRole('status')).toHaveText('0 tasks left');
});
```

Playwright uses the same role-based locators as RTL, so the skills transfer. Its `expect` **auto-retries** until the condition passes or times out, which removes most flaky `sleep` calls.

One-time browser download: `npm run e2e:install`. Then `npm run e2e`.

## 5\. Accessibility testing

Accessibility is checked on three levels:

1. **Semantic HTML first.** Real `<button>`, `<label>`, `<main>`, headings in order. This fixes most issues before any tool runs.
2. **Role-based queries** (above) act as a free accessibility check on every component test.
3. **axe-core** automatically scans the page for WCAG violations such as missing labels and low contrast:

```ts
import AxeBuilder from '@axe-core/playwright';

test('page has no detectable accessibility violations', async ({ page }) => {
  await page.goto('/');

  // Scan the error state too, not just the happy path
  await page.getByRole('button', { name: 'Add task' }).click();
  await expect(page.getByRole('alert')).toBeVisible();

  const results = await new AxeBuilder({ page })
    .withTags(['wcag2a', 'wcag2aa'])
    .analyze();

  expect(results.violations).toEqual([]);
});
```

Automated tools catch roughly a third to half of accessibility problems. They can't tell you whether alt text is meaningful or whether the tab order makes sense. Keep doing quick manual checks: tab through the page, zoom to 200%, and try a screen reader once.

## Project scripts

```json
{
  "scripts": {
    "dev": "vite",
    "test": "vitest",
    "test:run": "vitest run",
    "e2e": "playwright test",
    "e2e:install": "playwright install chromium"
  }
}
```

These are plain npm scripts with no shell-specific syntax, so they behave identically in PowerShell, CMD, Bash and zsh.

## Takeaways

- Use **Vitest** for speed and zero extra config in a Vite project.
- Use **React Testing Library** to test behavior the way users experience it.
- Use **Playwright** sparingly for critical, real-browser flows.
- Treat **accessibility** as part of correctness: semantic HTML, role-based queries and axe scans.
- Fewer, better-targeted tests beat chasing a coverage number.

*The complete code is in this* [*link*](https://github.com/leeonscoding/react-week9)*.*
