Lesson 9 of 11 · 12 min · Testing React
Testing components with Vitest and Testing Library
What you will learn
- Choose between Vitest and Jest and set up Vitest with
jsdom - Render a component and query the page the way a user finds things
- Use accessible queries (
getByRole,getByLabelText) andjest-domassertions - Write tests for conditional rendering and props
- Follow the testing philosophy: test behaviour, not implementation
In simple words
Component tests check that your screen behaves correctly: a button shows the right text, an error appears when it should. A test renders your component in a pretend browser, looks for things by what a person would see, such as "the button called Save" or "the field labelled Email", and checks the result. Because it looks for things the way users and screen readers do, the tests also nudge you toward accessible code.
Words to know
- Test runner: the tool that finds and runs your tests and reports results (Vitest, Jest).
- jsdom: a simulated browser environment that runs in Node.js for tests.
- React Testing Library: a library that renders components and finds elements the way users do.
- Assertion: a check in a test that something is true.
Vitest or Jest?
Both are test runners with a similar API (describe, it, expect). Vitest is built on Vite, so it reuses your Vite configuration and is fast, with first-class TypeScript and ES module support, and is the usual choice for new Vite projects. Jest is older and common in existing codebases and in Create React App and Next.js projects; it needs Babel or SWC setup for TypeScript and JSX. Most examples here use Vitest; the Testing Library parts are identical in Jest, and nearly all test code moves between them with small changes (vi.fn() becomes jest.fn(), vi.mock becomes jest.mock).
Setup with Vitest
npm install -D vitest jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event
// vite.config.ts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom", // a simulated DOM
globals: true, // describe, it, expect without imports (optional)
setupFiles: "./src/test/setup.ts",
css: false,
},
});
// src/test/setup.ts
import "@testing-library/jest-dom/vitest"; // adds matchers such as toBeInTheDocument
import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
afterEach(() => cleanup()); // unmount components between tests (automatic with globals: true)
// package.json
{ "scripts": { "test": "vitest", "test:run": "vitest run", "coverage": "vitest run --coverage" } }
If you use TypeScript with globals: true, add "types": ["vitest/globals", "@testing-library/jest-dom"] to tsconfig.json. Run npm test for watch mode (re-runs affected tests as you edit).
A first test
// CourseCard.tsx
type Props = { title: string; lessons: number; free?: boolean };
export function CourseCard({ title, lessons, free = false }: Props) {
return (
<article>
<h3>{title}</h3>
<p>{lessons} lessons</p>
{free && <span>Free</span>}
</article>
);
}
// CourseCard.test.tsx
import { render, screen } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { CourseCard } from "./CourseCard";
describe("CourseCard", () => {
it("shows the title and the number of lessons", () => {
render(<CourseCard title="SQL for analysts" lessons={14} />);
expect(screen.getByRole("heading", { name: "SQL for analysts" })).toBeInTheDocument();
expect(screen.getByText("14 lessons")).toBeInTheDocument();
});
it("shows a Free badge only for free courses", () => {
const { rerender } = render(<CourseCard title="Intro" lessons={3} free />);
expect(screen.getByText("Free")).toBeInTheDocument();
rerender(<CourseCard title="Intro" lessons={3} />);
expect(screen.queryByText("Free")).not.toBeInTheDocument(); // queryBy returns null when absent
});
});
The pattern is arrange (render), act (interact; next lesson) and assert (expect). render mounts the component in a document.body container; screen is the page you query.
Queries: find things like a user
Testing Library offers three families, each with ByX variants:
| Prefix | Returns | If not found | Use for |
|---|---|---|---|
getBy... |
one element | throws | things that must be present |
queryBy... |
one element or null |
null |
asserting that something is absent |
findBy... |
a promise | rejects after a timeout | things that appear asynchronously |
(getAllBy, queryAllBy, findAllBy for several.)
Priority order recommended by the Testing Library docs (most to least preferred):
getByRolewith an accessible name:getByRole("button", { name: /save/i }),getByRole("heading", { level: 2 }),getByRole("textbox", { name: "Email" }),getByRole("link", { name: "Courses" }),getByRole("checkbox"). This is how assistive technology sees the page.getByLabelTextfor form fields:getByLabelText("Email").getByPlaceholderText(weaker: placeholders are not labels).getByTextfor non-interactive content:getByText("14 lessons"),getByText(/lessons/i).getByDisplayValue,getByAltText,getByTitle.getByTestId(data-testid="...") only as a last resort when nothing user-facing identifies the element.
Why: tests that find elements by role and name break only when what users perceive changes, not when you rename a CSS class or reorganise the markup; and if getByRole("button", { name: "Save" }) fails, it often reveals a real accessibility problem (no label, wrong element). Use screen.debug() to print the DOM, and screen.logTestingPlaygroundURL() or the Testing Playground to suggest the best query. Matching text with a regular expression (/save/i) is more forgiving than exact strings.
jest-dom assertions
@testing-library/jest-dom adds readable matchers for DOM state:
expect(element).toBeInTheDocument();
expect(element).toBeVisible();
expect(button).toBeDisabled(); // toBeEnabled()
expect(input).toHaveValue("asha@example.com");
expect(checkbox).toBeChecked();
expect(link).toHaveAttribute("href", "/courses");
expect(element).toHaveTextContent(/paid/i);
expect(field).toHaveAccessibleName("Email");
expect(field).toBeInvalid(); // aria-invalid or constraint validation
expect(heading).toHaveClass("title"); // avoid asserting on styling details
Use the built-in Vitest expect for everything else (toBe, toEqual, toHaveBeenCalledWith, toHaveLength, toThrow).
What to test
Test behaviour that matters to users, from the outside:
- Renders the right content for given props and states (loading, error, empty, success).
- Responds to interaction (clicks, typing, keyboard) with the right result.
- Conditional UI (an admin-only button, a disabled state, an error message).
- Accessibility basics: roles, labels, names.
- Integration of a few components (a form with its fields and submit button).
Avoid testing implementation details: the names of state variables, which hook is used, internal function calls, snapshot of a huge component tree, CSS class names. If you can refactor a component (rename state, swap useState for useReducer) without changing behaviour, no tests should fail. That is the sign of good tests. As the Testing Library guiding principle says: the more your tests resemble the way your software is used, the more confidence they can give you.
Snapshot tests (expect(container).toMatchSnapshot()) are cheap but brittle for UI; people approve changes without reading them. Use them sparingly for small stable output.
Organising tests
- Put
Component.test.tsxnext toComponent.tsx(or in__tests__). - Group with
describe; name tests as behaviours:it("disables Save while the form is invalid"). - Share setup with a
renderWithProviders(ui)helper that wraps components in the router, query client and theme providers they need:
export function renderWithProviders(ui: React.ReactElement) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); // no retries in tests
return render(
<QueryClientProvider client={client}>
<MemoryRouter>{ui}</MemoryRouter>
</QueryClientProvider>
);
}
- Use
MemoryRouter(orcreateMemoryRouter) to test components with links and routes. - Each test must be independent: fresh render, no shared mutable state, cleanup between tests.
- Keep tests fast and deterministic: no real network (mock it in the third lesson), no real timers (use
vi.useFakeTimers()), no dependence on the current date. - Use coverage (
vitest run --coverage, with the@vitest/coverage-v8package) as a map of untested code, not a score to chase (the Java testing course discusses this).
Jest differences in brief
| Vitest | Jest | |
|---|---|---|
| Mock functions | vi.fn(), vi.spyOn() |
jest.fn(), jest.spyOn() |
| Module mocks | vi.mock("./api") (hoisted) |
jest.mock("./api") |
| Timers | vi.useFakeTimers() |
jest.useFakeTimers() |
| Config | in vite.config.ts |
jest.config.js |
| Globals | opt in with globals: true |
on by default |
| jest-dom import | @testing-library/jest-dom/vitest |
@testing-library/jest-dom |
| ESM and TypeScript | native | needs Babel or ts-jest or SWC |
Common mistakes
- Using
getByTestIdfor everything. - Asserting on implementation details (state, class names).
- Using
getByto assert absence (it throws; usequeryBy). - Forgetting
findByorwaitForfor async UI, causing flaky tests. - Sharing state between tests or forgetting cleanup.
- Testing the library (that React renders a prop) rather than your behaviour.
- Snapshots of large components that nobody reviews.
Try it yourself
- Set up Vitest, jsdom and Testing Library in a Vite React project and make the sample test pass.
- Write tests for a component with loading, error and success props using
getByRoleandqueryByText. - Make a test fail on purpose and read the DOM output Testing Library prints.
- Refactor a component's internals (rename a state variable) and check that no test fails.
- Create
renderWithProvidersand use it for a component that uses the router.
Check yourself
Why prefer getByRole to getByTestId?
Roles and accessible names reflect what users and assistive technology perceive, so tests break only on real behaviour changes and expose accessibility problems; test ids are invisible to users and are a last resort.
What is the difference between getBy, queryBy and findBy?
getBy returns an element or throws; queryBy returns an element or null (use it to assert absence); findBy returns a promise for elements that appear asynchronously.
What should component tests focus on?
Observable behaviour from the user's perspective, not implementation details such as state or internal function calls.
What does the jsdom test environment provide?
A simulated browser DOM running in Node.js, so components can render and be queried without a real browser.
Interview questions
How do you test a React component?
Render it with React Testing Library inside a Vitest or Jest run, query elements by role, label or text as a user would, interact with them, and assert on the resulting DOM with jest-dom matchers, mocking external dependencies such as network calls.
What is the guiding principle of React Testing Library?
Tests should resemble how users use the software, so they query by accessible roles and text and avoid implementation details, giving more confidence and less brittleness when refactoring.
Vitest versus Jest: when do you choose which?
Vitest for Vite-based projects (shared config, speed, native ESM and TypeScript); Jest when the project already uses it or needs its ecosystem; the Testing Library code is the same in both.
Summary
- Use Vitest (or Jest) with jsdom and React Testing Library; add
jest-domfor readable assertions. - Query by role, label and text;
getBythrows,queryBychecks absence,findBywaits. - Test user-visible behaviour, not implementation; use helpers to provide router and query client.
- Keep tests independent, fast and deterministic; use coverage as a guide.
Going deeper
- Vitest: Getting started: installation, configuration and the test API.
- Testing Library: React introduction: setup and principles.
- Testing Library: Queries: priority of queries and variants.
- jest-dom matchers: the full list of DOM assertions.
See how much of this you can explain
A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.