Write maintainable, user-centric tests for React components using Testing Library and Jest.
# React Testing Library Best Practices
Master React component testing with Testing Library using Google Antigravity IDE. This comprehensive guide covers testing patterns, user interactions, and accessibility-first testing strategies.
## Why React Testing Library?
Testing Library encourages testing from the user's perspective. Google Antigravity IDE's Gemini 3 engine generates comprehensive tests and suggests accessibility improvements.
## Test Setup
```typescript
// src/test/setup.ts
import "@testing-library/jest-dom";
import { cleanup } from "@testing-library/react";
import { afterEach, vi } from "vitest";
// Cleanup after each test
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
// Mock window.matchMedia
Object.defineProperty(window, "matchMedia", {
writable: true,
value: vi.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
// Mock ResizeObserver
global.ResizeObserver = vi.fn().mockImplementation(() => ({
observe: vi.fn(),
unobserve: vi.fn(),
disconnect: vi.fn(),
}));
```
## Custom Render Function
```typescript
// src/test/utils.tsx
import { render, RenderOptions } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter } from "react-router-dom";
import { ThemeProvider } from "@/contexts/ThemeContext";
import { AuthProvider } from "@/contexts/AuthContext";
interface CustomRenderOptions extends Omit<RenderOptions, "wrapper"> {
initialRoute?: string;
user?: User | null;
}
function createTestQueryClient() {
return new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
}
export function renderWithProviders(
ui: React.ReactElement,
options: CustomRenderOptions = {}
) {
const { initialRoute = "/", user = null, ...renderOptions } = options;
window.history.pushState({}, "Test page", initialRoute);
const queryClient = createTestQueryClient();
function Wrapper({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<AuthProvider initialUser={user}>
<ThemeProvider>
{children}
</ThemeProvider>
</AuthProvider>
</BrowserRouter>
</QueryClientProvider>
);
}
return {
...render(ui, { wrapper: Wrapper, ...renderOptions }),
queryClient,
};
}
export * from "@testing-library/react";
export { renderWithProviders as render };
```
## Component Testing
```typescript
// components/LoginForm.test.tsx
import { render, screen, waitFor } from "@/test/utils";
import userEvent from "@testing-library/user-event";
import { LoginForm } from "./LoginForm";
describe("LoginForm", () => {
const mockOnSubmit = vi.fn();
beforeEach(() => {
mockOnSubmit.mockClear();
});
it("renders email and password fields", () => {
render(<LoginForm onSubmit={mockOnSubmit} />);
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
expect(screen.getByRole("button", { name: /sign in/i })).toBeInTheDocument();
});
it("shows validation errors for empty fields", async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={mockOnSubmit} />);
await user.click(screen.getByRole("button", { name: /sign in/i }));
expect(await screen.findByText(/email is required/i)).toBeInTheDocument();
expect(await screen.findByText(/password is required/i)).toBeInTheDocument();
expect(mockOnSubmit).not.toHaveBeenCalled();
});
it("submits form with valid data", async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={mockOnSubmit} />);
await user.type(screen.getByLabelText(/email/i), "test@example.com");
await user.type(screen.getByLabelText(/password/i), "password123");
await user.click(screen.getByRole("button", { name: /sign in/i }));
await waitFor(() => {
expect(mockOnSubmit).toHaveBeenCalledWith({
email: "test@example.com",
password: "password123",
});
});
});
it("disables submit button while loading", async () => {
render(<LoginForm onSubmit={mockOnSubmit} isLoading />);
expect(screen.getByRole("button", { name: /signing in/i })).toBeDisabled();
});
});
```
## Async Testing
```typescript
// components/UserProfile.test.tsx
import { render, screen, waitForElementToBeRemoved } from "@/test/utils";
import { rest } from "msw";
import { setupServer } from "msw/node";
import { UserProfile } from "./UserProfile";
const server = setupServer(
rest.get("/api/users/:id", (req, res, ctx) => {
return res(
ctx.json({
id: req.params.id,
name: "John Doe",
email: "john@example.com",
})
);
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
describe("UserProfile", () => {
it("loads and displays user data", async () => {
render(<UserProfile userId="123" />);
// Wait for loading state to disappear
await waitForElementToBeRemoved(() => screen.queryByText(/loading/i));
expect(screen.getByText("John Doe")).toBeInTheDocument();
expect(screen.getByText("john@example.com")).toBeInTheDocument();
});
it("displays error message on failure", async () => {
server.use(
rest.get("/api/users/:id", (req, res, ctx) => {
return res(ctx.status(500), ctx.json({ error: "Server error" }));
})
);
render(<UserProfile userId="123" />);
expect(await screen.findByText(/error loading user/i)).toBeInTheDocument();
});
});
```
## Accessibility Testing
```typescript
import { axe, toHaveNoViolations } from "jest-axe";
expect.extend(toHaveNoViolations);
describe("Accessibility", () => {
it("has no accessibility violations", async () => {
const { container } = render(<LoginForm onSubmit={vi.fn()} />);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
});
```
## Best Practices
- Query by role, label, or text (user perspective)
- Use userEvent over fireEvent for realistic interactions
- Test behavior, not implementation details
- Mock API calls with MSW
- Include accessibility testing with jest-axe
- Create custom render with providers
Google Antigravity IDE generates comprehensive test cases and suggests accessibility improvements for your React components.This React prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their react implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For React projects, consider mentioning your framework version, coding style, and any specific libraries you're using.