Lesson 5 of 7
React Component Testing with TypeScript
Testing React components requires a testing library that renders JSX and provides typed query helpers. `@testing-library/react` is the standard. With TypeScript, all `render`, `screen`, `fireEvent`, and `userEvent` calls are typed - missing required props become compile errors before the test runs.
React Testing Library + TypeScript
React Testing Library + TypeScript
# npm install --save-dev @testing-library/react @testing-library/user-event @testing-library/jest-dom
// ── Setup - extend Jest matchers ─────────────────────────────
// In jest.setup.ts:
import "@testing-library/jest-dom";
// Adds: toBeInTheDocument, toHaveValue, toBeVisible, etc.
// These matchers are typed by @types/testing-library__jest-dom
// ── Component test - fully typed ─────────────────────────────
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { CreateTaskForm } from "@/components/CreateTaskForm";
describe("CreateTaskForm", () => {
it("calls onCreate with trimmed title and priority", async () => {
const user = userEvent.setup();
const onCreate = jest.fn<
void,
[Pick<Task, "title" | "priority">]
>();
// render is typed - missing required props = compile error
render(<CreateTaskForm onCreate={onCreate} />);
const titleInput = screen.getByPlaceholderText("Task title...");
const prioritySelect = screen.getByRole("combobox");
const submitButton = screen.getByRole("button", { name: /create/i });
// userEvent is async in v14+
await user.type(titleInput, " Launch feature ");
await user.selectOptions(prioritySelect, "high");
await user.click(submitButton);
await waitFor(() => {
expect(onCreate).toHaveBeenCalledWith({
title: "Launch feature", // trimmed
priority: "high",
});
});
});
it("does not submit when title is empty", async () => {
const user = userEvent.setup();
const onCreate = jest.fn();
render(<CreateTaskForm onCreate={onCreate} />);
await user.click(screen.getByRole("button", { name: /create/i }));
expect(onCreate).not.toHaveBeenCalled();
});
});
// ── Testing async components ──────────────────────────────────
import { TaskDetail } from "@/components/TaskDetail";
describe("TaskDetail", () => {
it("shows task title after loading", async () => {
// Mock the API
jest.mocked(taskApi.getById).mockResolvedValue({
id: 1, title: "Write tests", status: "todo", priority: "high",
} as Task);
render(<TaskDetail taskId={1} />);
// Loading state
expect(screen.getByText(/loading/i)).toBeInTheDocument();
// After async resolution
await screen.findByText("Write tests"); // findBy* is async
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
});
});Diagram
Loading diagram…
Visual architecture and concepts for React Component Testing with TypeScript
Common Mistakes
- Using `getByText` for async content - `getBy*` throws immediately if not found. For async content, use `findBy*` (returns a Promise, waits with timeout) or wrap in `waitFor`.
- Testing implementation details - `fireEvent.click(button)` directly is fine, but don't test internal state via refs or enzyme-style shallow rendering. Test what the user sees and can interact with.
- Not wrapping state updates in `act()` - React Testing Library wraps most operations in `act()` automatically. If you see 'not wrapped in act' warnings, ensure your test awaits all async user interactions with `await`.
Key Takeaways
- Testing React components requires a testing library that renders JSX and provides typed query helpers.
- Using `getByText` for async content - `getBy*` throws immediately if not found. For async content, use `findBy*` (returns a Promise, waits with timeout) or wrap in `waitFor`.
- Testing implementation details - `fireEvent.click(button)` directly is fine, but don't test internal state via refs or enzyme-style shallow rendering. Test what the user sees and can interact with.
- Not wrapping state updates in `act()` - React Testing Library wraps most operations in `act()` automatically. If you see 'not wrapped in act' warnings, ensure your test awaits all async user interactions with `await`.
Finished this lesson?
0 of 7 in Module 11