React Component Tests With Vitest and Testing Library: Test What the User Sees
Four component tests for a React task board: the four-line Vitest config, a render-find-act-check test, the real failure when a test asks for 'Add' but the page says 'add', and a vi.fn spy for one component on its own.
What you will learn
- Explain why a component test should use only what the user sees
- Wire Vitest, jsdom and Testing Library together in vite.config.ts
- Write a render, find, act, check test with getByRole and user-event
- Read a failing test's accessible-roles list, and test one component with a vi.fn spy
Before you start
- React state, props and lifting state up
- Running npm scripts
Picture a mystery shopper walking into a small shop. They look at the window, read the signs, press a button and write down what happened. They never see the stock room. That is how a good React component test works: it uses the page the way a person would, and never looks at state, setters or helper functions behind it.
This article tests the task board from lifting state up: three filter buttons, a counter that says "5 of 5 shown", and a text box with an add button. Every test name, error and count below comes from the project's own test run.
Test only what the user sees
Three tools, one job each
- Vitest finds files ending in
.test.tsx, runs every test in them and reports pass or fail. - jsdom gives each test a web page that exists only in memory. No screen, no window, just the page.
- Testing Library draws the component into that page, then finds, clicks and checks things like a person would.
The wiring is one small block in the Vite config:
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vitest/config'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: './src/test-setup.ts',
},
})
environment: 'jsdom' gives every test that in-memory page. setupFiles names a file that runs before every test file:
import '@testing-library/jest-dom/vitest'
import { cleanup } from '@testing-library/react'
import { afterEach } from 'vitest'
// start every test on a clean page
afterEach(cleanup)
It adds matchers such as toBeInTheDocument, and cleans the page after every test so one test never leaks into the next. The test script in package.json is vitest run --reporter=verbose.
Render, find, act, check
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expect, test } from 'vitest'
import App from './App'
test('shows every task at the start', () => {
render(<App />)
expect(screen.getByText('5 of 5 shown')).toBeInTheDocument()
expect(screen.getByText(/Write report/)).toBeInTheDocument()
})
test('the done filter hides the open tasks', async () => {
const user = userEvent.setup()
render(<App />)
await user.click(screen.getByRole('button', { name: 'done' }))
expect(screen.getByRole('button', { name: 'done', pressed: true })).toBeInTheDocument()
expect(screen.getByText('2 of 5 shown')).toBeInTheDocument()
expect(screen.queryByText(/Email Jack/)).not.toBeInTheDocument()
})
test('adds a task from the text box', async () => {
const user = userEvent.setup()
render(<App />)
const box = screen.getByRole('textbox', { name: 'New task' })
await user.type(box, 'Pay rent')
await user.click(screen.getByRole('button', { name: 'add' }))
expect(screen.getByText(/Pay rent/)).toBeInTheDocument()
expect(screen.getByText('6 of 6 shown')).toBeInTheDocument()
})
Look at the third test. It has the four moves you'll see in almost every component test:
- Render: draw the whole app into the in-memory page.
- Find: ask for the text box by its role and name,
getByRole('textbox', { name: 'New task' }), the way a person would describe it. - Act: type "Pay rent" one letter at a time with
user.type, then click the button named add. - Check: the new task is on the page and the counter says 6 of 6 shown.
Nothing in it reads a variable. It only uses the page. The second test also checks pressed: true, which works because TaskFilter sets aria-pressed on the active button:
function TaskFilter({ value, onChange }: Props) {
return (
<div className="filters">
{FILTERS.map((f) => (
<button key={f}
aria-pressed={f === value}
className={f === value ? 'on' : ''}
onClick={() => onChange(f)}>
{f}
</button>
))}
</div>
)
}
Run it before you trust it
A test you have never seen fail is a test you can't fully trust. In the first draft, the test asked for the button with a capital A: { name: 'Add' }. Running npm test:
✓ src/App.test.tsx > shows every task at the start 60ms
✓ src/TaskFilter.test.tsx > reports a click on a filter button 318ms
✓ src/App.test.tsx > the done filter hides the open tasks 307ms
× src/App.test.tsx > adds a task from the text box 264ms
→ Unable to find an accessible element with the role "button" and name "Add"
Here are the accessible roles:
button:
Name "all":
Name "open":
Name "done":
Name "add":
...
textbox:
Name "New task":
Test Files 1 failed | 1 passed (2)
Tests 1 failed | 3 passed (4)
(The role list is shortened here; the real output also prints each element's HTML and the paragraph, list and list items.) The failure message is a picture of what a user can actually find on the page. The test asked for "Add", but the list has "add". It even points at the line:
❯ src/App.test.tsx:26:27
26| await user.click(screen.getByRole('button', { name: 'Add' }))
| ^
Change one letter to 'add' and run again:
✓ src/TaskFilter.test.tsx > reports a click on a filter button 372ms
✓ src/App.test.tsx > shows every task at the start 70ms
✓ src/App.test.tsx > the done filter hides the open tasks 400ms
✓ src/App.test.tsx > adds a task from the text box 275ms
Test Files 2 passed (2)
Tests 4 passed (4)
It failed first and passed after, so we know it can catch a real mistake.
A component on its own, with a spy
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expect, test, vi } from 'vitest'
import TaskFilter from './TaskFilter'
test('reports a click on a filter button', async () => {
const user = userEvent.setup()
const onChange = vi.fn() // a spy
render(<TaskFilter value="all" onChange={onChange} />)
await user.click(screen.getByRole('button', { name: 'open' }))
expect(onChange).toHaveBeenCalledWith('open')
})
Not every test needs the whole app. TaskFilter changes nothing by itself; it tells its parent through onChange. So the test hands it a fake function made with vi.fn(). A spy remembers how it was called. Click open, and the spy confirms the component told its parent "open".
Find things the way a user does
| Query | When | Example from the tests |
|---|---|---|
getByRole with a name | First choice | the button named done |
getByText | Plain text | 5 of 5 shown |
queryByText | Checking something is gone; returns null instead of throwing | Email Jack after picking done |
Asking for a role and a name keeps the test close to the user, and it nudges you to build pages that work with screen readers too. Notice the input needed aria-label="New task" to have that name.
Recap
| Idea | What to remember |
|---|---|
| The rule | Test what the user sees, not how it is built |
| Wiring | environment: 'jsdom' and a setupFiles entry |
| Shape | Render, find, act, check |
| Acting | userEvent.setup(), then await user.type and user.click |
| Trust | See the test fail once; the accessible-roles list shows what the page offers |
| Spies | vi.fn() checks what a component told its parent |
Try it yourself: add a test that clicks open and checks that "3 of 5 shown" appears and "Write report" is gone. Then break it on purpose before you trust it. Component tests run in memory; for a real browser, see end-to-end tests with Playwright.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
Semantic HTML: header, nav, main, aside and footer as Page Landmarks
The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.
