Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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

What a component test may touch Shop front: the test uses this button named "done" text "5 of 5 shown" textbox named "New task" Back room: never filter state setFilter matches()
Rename anything in the back room and the shopper doesn't care. Neither should the test.

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:

  1. Render: draw the whole app into the in-memory page.
  2. Find: ask for the text box by its role and name, getByRole('textbox', { name: 'New task' }), the way a person would describe it.
  3. Act: type "Pay rent" one letter at a time with user.type, then click the button named add.
  4. 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

QueryWhenExample from the tests
getByRole with a nameFirst choicethe button named done
getByTextPlain text5 of 5 shown
queryByTextChecking something is gone; returns null instead of throwingEmail 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

IdeaWhat to remember
The ruleTest what the user sees, not how it is built
Wiringenvironment: 'jsdom' and a setupFiles entry
ShapeRender, find, act, check
ActinguserEvent.setup(), then await user.type and user.click
TrustSee the test fail once; the accessible-roles list shows what the page offers
Spiesvi.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.

Keep going in React · 18 of 59

Previous
Routing With React Router: One Page, Many Addresses
Next post
End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Test only what the user sees
  • Three tools, one job each
  • Render, find, act, check
  • Run it before you trust it
  • A component on its own, with a spy
  • Find things the way a user does
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.