Testing React
Clicking through every screen after every change does not scale. Automated tests check the app in seconds with one command. This note covers Vitest + React Testing Library, the AAA pattern, getBy/queryBy/findBy, mocking APIs with MSW and an intro to E2E with Playwright.
54.1 Why is it used?
- A real app has 100+ screens; checking each by hand after every change is not practical.
- A small refactor can break another feature and the bug goes straight to production, where users find it first.
- Automated tests are code: one command checks the whole app in a few seconds.
- Step 1
1.Code change: refactor or new feature
- Step 2
2.Without tests: manual check of 100+ screens, nobody does it
- Step 3
3.Bug reaches production, users find it first
- Step 4
4.With tests: npx vitest run in CI on every change
- Step 5
5.Broken behaviour fails a test before merge
54.2 The component under test
import { useState } from "react"; export function CartButton() { const [qty, setQty] = useState(0); return ( <div> <p>In cart: {qty}</p> <button onClick={() => setQty(qty + 1)}> Add to cart </button> </div> );}In cart: 0[button] Add to cart In cart: 1[button] Add to cart54.3 Setup: Vitest + Testing Library
- Vitest: fast test runner for Vite projects; config goes in a test block in vite.config.js.
- environment: "jsdom" gives a fake browser DOM inside Node.
- globals: true gives test and expect without importing them.
- The setup file imports @testing-library/jest-dom, which adds matchers like toBeInTheDocument.
npm i -D vitest jsdomnpm i -D @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-domimport { defineConfig } from "vite";import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], test: { environment: "jsdom", globals: true, setupFiles: "./setupTests.js", },});// setupTests.jsimport "@testing-library/jest-dom";54.4 First test (AAA pattern)
- The test file lives next to the component: CartButton.test.jsx.
- userEvent.setup() creates a user who clicks and types like a real user.
- render mounts the component into the fake DOM.
- getByRole finds the button by role and name, just like a user or screen reader sees it.
- await user.click(btn), then expect the text In cart: 1 to be in the document.
import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { CartButton } from "./CartButton"; test("adds one item on click", async () => { const user = userEvent.setup(); render(<CartButton />); const btn = screen.getByRole("button", { name: /add to cart/i, }); await user.click(btn); expect(screen.getByText("In cart: 1")) .toBeInTheDocument();});$ npx vitest run ✓ CartButton.test.jsx (1 test) Test Files 1 passed (1) Tests 1 passed (1)- Step 1
1.Arrange: render(<CartButton />) + userEvent.setup()
- Step 2
2.Act: await user.click(...) / user.type(...)
- Step 3
3.Assert: expect(screen.getByText(...)).toBeInTheDocument()
Every good test follows these three steps
54.5 getBy, queryBy, findBy
| Query | Not found | Async? | Use when |
|---|---|---|---|
| getBy... | Throws an error immediately | No | The element must be on screen right now |
| queryBy... | Returns null | No | Checking that an element is NOT on screen |
| findBy... | Rejects after waiting (timeout) | Yes, returns a Promise | Element appears later (API data); use with await |
// getBy: must be there now, else errorscreen.getByRole("button", { name: /pay/i }); // queryBy: may be missing, gives nullexpect(screen.queryByText(/error/i)) .not.toBeInTheDocument(); // findBy: waits for it, returns a Promiseexpect(await screen.findByText(/welcome/i)) .toBeInTheDocument();54.6 MSW: a fake API response
- Calling the real server in tests is slow and unreliable.
- MSW (Mock Service Worker) intercepts the request at the network level and returns a fake response.
- setupServer has a handler: GET https://api.shop.in/users returns [{ id: 1, name: "Asha" }].
- server.listen() in beforeAll, server.close() in afterAll; findByText waits until Asha appears.
import { http, HttpResponse } from "msw";import { setupServer } from "msw/node"; const server = setupServer( http.get("https://api.shop.in/users", () => HttpResponse.json([{ id: 1, name: "Asha" }]) ));beforeAll(() => server.listen());afterAll(() => server.close());test("shows users from the API", async () => { render(<UserList />); expect(await screen.findByText("Asha")) .toBeInTheDocument();});$ npx vitest run UserList ✓ UserList.test.jsx (1 test) Test Files 1 passed (1)- Step 1
1.render(<UserList />): first render, list is empty
- Step 2
2.Component calls fetch("https://api.shop.in/users")
- Step 3
3.MSW intercepts the request at the network level
- Step 4
4.Handler returns [{ id: 1, name: "Asha" }]
- Step 5
5.Component re-renders, findByText("Asha") resolves, test passes
54.7 Checkpoint: getBy for async data
- Replace findByText with getByText and remove await: the test fails.
- On the first render the list is empty; the data arrives a little later and getBy does not wait.
- That is exactly why async data uses findBy.
test("shows users from the API", () => { render(<UserList />); expect(screen.getByText("Asha")) .toBeInTheDocument();});× shows users from the APIUnable to find an element with the text: AshaScreen: the list is still empty54.8 Playwright: E2E intro
- End to end (E2E) tests check the whole app in a real browser.
- page.goto("/") opens the homepage like a real tab; getByRole finds the button; toBeVisible checks the result.
- E2E tests are slow, so write them only for important flows.
import { test, expect } from "@playwright/test"; test("adds to cart", async ({ page }) => { await page.goto("/"); const add = page.getByRole("button", { name: "Add to cart", }); await add.click(); await expect(page.getByText("In cart: 1")) .toBeVisible();});| Point | Component test (Vitest + RTL) | E2E (Playwright) |
|---|---|---|
| Runs in | Node + jsdom (fake DOM) | Real browser |
| Speed | Fast (ms per test) | Slow (seconds per test) |
| APIs | Mocked with MSW | Real or staging backend |
| Write for | Most components and logic | Critical flows: login, cart, payment |
54.9 Common mistakes
- Testing implementation details: querySelector on tags + fireEvent. Change a p to a span and the test fails although the feature still works.
- Test like a user: getByRole / getByText and userEvent, because a user sees text, not tags.
- Forgetting await on userEvent calls or findBy queries.
- Chasing 100% coverage: coverage only says which lines ran, not whether their result was checked.
// Wrong: depends on tags and DOM structureconst { container } = render(<CartButton />);const btn = container.querySelector("button");fireEvent.click(btn);const p = container.querySelector("p");expect(p.textContent).toBe("In cart: 1");// Right: tests what the user seesconst user = userEvent.setup();render(<CartButton />);await user.click(screen.getByRole("button"));expect(screen.getByText("In cart: 1")) .toBeInTheDocument();54.10 Best practices
- Test what the user sees and does, not internal state or functions.
- Query priority: getByRole and getByLabelText first, test id last.
- Always await userEvent calls.
- Use MSW for APIs instead of mocking fetch by hand.
- Focus on meaningful tests for important flows: login, cart, payment.
54.11 Interview tips
- "How do you test React components?" Vitest as runner, React Testing Library for components, queries by role and label so tests do not depend on implementation details.
- MSW for API mocking, Playwright E2E for critical flows.
- Explain getBy (throws now) vs queryBy (null, for absence) vs findBy (waits, Promise).
- Every test = Arrange, Act, Assert.
- 100% coverage does not mean bug-free.