/frontend-react:react-testingfrom frontend-react
React testing with Vitest, React Testing Library, and Playwright — configuration, patterns, co-location, hooks testing, Server Component testing, snapshot guidance, and coverage targets.
Ships in frontend-react. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Maintain >= 85% code coverage across unit and integration tests. Enforce via CI:
// vitest.config.ts
coverage: {
thresholds: { lines: 85, functions: 85, branches: 80, statements: 85 },
}
Vitest is the standard test runner for React/Vite and Next.js projects.
// vitest.config.ts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./src/test/setup.ts"],
include: ["src/**/*.{test,spec}.{ts,tsx}"],
coverage: {
provider: "v8",
reporter: ["text", "html", "lcov"],
include: ["src/**/*.{ts,tsx}"],
exclude: ["src/**/*.d.ts", "src/**/index.ts", "src/test/**"],
thresholds: { lines: 85, functions: 85, branches: 80 },
},
},
resolve: {
alias: { "@": path.resolve(__dirname, "./src") },
},
});
// src/test/setup.ts
import "@testing-library/jest-dom";
import { cleanup } from "@testing-library/react";
import { afterEach, vi } from "vitest";
afterEach(() => {
cleanup();
});
// Stub browser APIs not available in jsdom
Object.defineProperty(window, "matchMedia", {
value: vi.fn().mockImplementation(query => ({
matches: false,
media: query,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
})),
});
import { describe, it, expect, vi, beforeEach } from "vitest";
describe("formatPrice", () => {
it("formats a price in USD", () => {
expect(formatPrice(1099, "USD")).toBe("$10.99");
});
it("returns free for zero amount", () => {
expect(formatPrice(0, "USD")).toBe("Free");
});
it("throws on negative amount", () => {
expect(() => formatPrice(-1, "USD")).toThrow("negative");
});
});
import { vi } from "vitest";
// Module mock
vi.mock("@/lib/api", () => ({
fetchUser: vi.fn().mockResolvedValue({ id: "1", name: "Alice" }),
}));
// Partial mock
vi.mock("next/navigation", async (importOriginal) => {
const actual = await importOriginal<typeof import("next/navigation")>();
return {
...actual,
useRouter: vi.fn().mockReturnValue({
push: vi.fn(),
replace: vi.fn(),
back: vi.fn(),
refresh: vi.fn(),
}),
usePathname: vi.fn().mockReturnValue("/dashboard"),
};
});
// Clear between tests
beforeEach(() => {
vi.clearAllMocks();
});
@testing-library/user-event.import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Button } from "./Button";
describe("Button", () => {
it("renders its label", () => {
render(<Button onClick={vi.fn()}>Save Changes</Button>);
expect(screen.getByRole("button", { name: "Save Changes" })).toBeInTheDocument();
});
it("calls onClick when clicked", async () => {
const user = userEvent.setup();
const handleClick = vi.fn();
render(<Button onClick={handleClick}>Save</Button>);
await user.click(screen.getByRole("button", { name: "Save" }));
expect(handleClick).toHaveBeenCalledOnce();
});
it("is disabled when loading", () => {
render(<Button loading>Save</Button>);
expect(screen.getByRole("button")).toBeDisabled();
});
});
getByRole — query by ARIA role + accessible namegetByLabelText — form elements associated with a labelgetByPlaceholderText — fallback for unlabelled inputsgetByText — visible text contentgetByDisplayValue — current input valuegetByAltText — image altgetByTitle — title attributegetByTestId — last resort, requires data-testidPrefer @testing-library/user-event over fireEvent — it simulates real browser events including pointerdown, focus, blur:
const user = userEvent.setup();
await user.type(screen.getByLabelText("Email"), "[email protected]");
await user.selectOptions(screen.getByRole("combobox", { name: "Role" }), "admin");
await user.keyboard("{Tab}");
await user.click(screen.getByRole("button", { name: "Submit" }));
import { waitFor, screen } from "@testing-library/react";
it("shows the user name after fetching", async () => {
render(<UserProfile userId="1" />);
// Wait for async state change
await waitFor(() => {
expect(screen.getByText("Alice")).toBeInTheDocument();
});
});
// findBy* is shorthand for getBy* wrapped in waitFor
it("shows success toast after save", async () => {
const user = userEvent.setup();
render(<SettingsForm />);
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("alert", { name: /saved/i })).toBeInTheDocument();
});
// src/test/test-utils.tsx
import { render, type RenderOptions } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "@/components/ThemeProvider";
function AllProviders({ children }: { children: React.ReactNode }) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider>{children}</ThemeProvider>
</QueryClientProvider>
);
}
export function renderWithProviders(ui: React.ReactElement, options?: RenderOptions) {
return render(ui, { wrapper: AllProviders, ...options });
}
export * from "@testing-library/react";
Use renderHook from @testing-library/react:
import { renderHook, act } from "@testing-library/react";
import { useCounter } from "./useCounter";
describe("useCounter", () => {
it("initialises with 0", () => {
const { result } = renderHook(() => useCounter());
expect(result.current.count).toBe(0);
});
it("increments the count", () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
it("resets to initialValue", () => {
const { result } = renderHook(() => useCounter(10));
act(() => {
result.current.increment();
result.current.reset();
});
expect(result.current.count).toBe(10);
});
});
For hooks that require context providers, pass a wrapper:
const { result } = renderHook(() => useCartStore(), {
wrapper: ({ children }) => <StoreProvider>{children}</StoreProvider>,
});
Server Components are async functions. Test them directly by calling them and awaiting the result, then asserting on the rendered output:
// PostPage.test.tsx
import { render, screen } from "@testing-library/react";
import PostPage from "@/app/posts/[id]/page";
vi.mock("@/lib/db", () => ({
db: {
post: {
findUnique: vi.fn().mockResolvedValue({ id: "1", title: "Hello World", body: "..." }),
},
},
}));
it("renders the post title", async () => {
const page = await PostPage({ params: Promise.resolve({ id: "1" }) });
render(page);
expect(screen.getByRole("heading", { name: "Hello World" })).toBeInTheDocument();
});
For complex Server Components that call multiple APIs, mock at the module boundary:
vi.mock("@/lib/posts", () => ({
getPost: vi.fn().mockResolvedValue({ id: "1", title: "Mocked" }),
}));
// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./e2e",
fullyParallel: true,
reporter: [["html"], ["github"]],
use: {
baseURL: "http://localhost:3000",
trace: "on-first-retry",
screenshot: "only-on-failure",
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "mobile", use: { ...devices["iPhone 14"] } },
],
webServer: {
command: "npm run dev",
url: "http://localhost:3000",
reuseExistingServer: !process.env.CI,
},
});
// e2e/fixtures.ts
import { test as base } from "@playwright/test";
type Fixtures = {
authenticatedPage: Page;
};
export const test = base.extend<Fixtures>({
authenticatedPage: async ({ page }, use) => {
await page.goto("/login");
await page.fill('[name="email"]', "[email protected]");
await page.fill('[name="password"]', "password");
await page.click('button[type="submit"]');
await page.waitForURL("/dashboard");
await use(page);
},
});
export { expect } from "@playwright/test";
Prefer user-facing locators:
// ARIA role (preferred)
await page.getByRole("button", { name: "Submit" }).click();
await page.getByRole("heading", { name: "Dashboard" }).waitFor();
// Label
await page.getByLabel("Email").fill("[email protected]");
// Text
await page.getByText("Welcome back").isVisible();
// Test ID (last resort)
await page.getByTestId("notification-banner").click();
await expect(page).toHaveURL("/dashboard");
await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
await expect(page.getByRole("status")).toContainText("Saved");
await expect(page.getByRole("button", { name: "Delete" })).toBeEnabled();
await expect(page.locator(".cart-count")).toHaveText("3");
await page.goto("/posts");
await page.getByRole("link", { name: "Create Post" }).click();
await page.waitForURL("/posts/new");
await page.goBack();
test("shows error when API fails", async ({ page }) => {
await page.route("**/api/posts", route =>
route.fulfill({ status: 500, body: JSON.stringify({ error: "Internal Server Error" }) })
);
await page.goto("/posts");
await expect(page.getByRole("alert")).toContainText("Failed to load");
});
test("intercepts and modifies response", async ({ page }) => {
await page.route("**/api/user/me", async route => {
const response = await route.fetch();
const json = await response.json();
await route.fulfill({ json: { ...json, name: "Test User" } });
});
await page.goto("/profile");
await expect(page.getByText("Test User")).toBeVisible();
});
Place tests next to the code they test:
src/
components/
Button/
Button.tsx
Button.test.tsx ← unit test
Button.module.css
hooks/
useCounter.ts
useCounter.test.ts ← hook test
e2e/
auth.spec.ts ← Playwright E2E
posts.spec.ts
Use snapshot tests selectively:
--updateSnapshot.import { render } from "@testing-library/react";
it("matches snapshot", () => {
const { container } = render(<Badge variant="success">Active</Badge>);
expect(container.firstChild).toMatchSnapshot();
});
Prefer inline snapshots for small outputs:
expect(formatDate(new Date("2025-01-01"))).toMatchInlineSnapshot(`"Jan 1, 2025"`);
| Do | Don't |
|---|---|
| Query by role, label, and text | Query by class name, CSS selector, or test ID unless necessary |
Use userEvent for interactions | Use fireEvent when userEvent is available |
Create a shared renderWithProviders utility | Repeat provider boilerplate in every test file |
| Mock at module boundaries | Reach into component internals or test implementation details |
| Write Playwright tests for critical user journeys | Write Playwright tests for every unit of logic |
| Review and commit deliberate snapshot updates | Auto-accept all snapshot updates without review |
| Enforce >= 85% coverage in CI | Let coverage drift without thresholds |
Structure each test file to cover positive, negative, edge, and security scenarios using React Testing Library.
describe("LoginForm", () => {
it("should submit successfully with valid credentials", async () => {
const onSubmit = vi.fn().mockResolvedValue({ success: true });
render(<LoginForm onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText("Email"), "[email protected]");
await userEvent.type(screen.getByLabelText("Password"), "validPass123");
await userEvent.click(screen.getByRole("button", { name: "Sign in" }));
expect(onSubmit).toHaveBeenCalledWith({
email: "[email protected]",
password: "validPass123",
});
});
it("should render all form fields and submit button", () => {
render(<LoginForm onSubmit={vi.fn()} />);
expect(screen.getByLabelText("Email")).toBeInTheDocument();
expect(screen.getByLabelText("Password")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Sign in" })).toBeEnabled();
});
});
describe("LoginForm", () => {
it("should display validation error for invalid email", async () => {
render(<LoginForm onSubmit={vi.fn()} />);
await userEvent.type(screen.getByLabelText("Email"), "not-an-email");
await userEvent.click(screen.getByRole("button", { name: "Sign in" }));
expect(screen.getByText("Invalid email address")).toBeInTheDocument();
});
it("should show error message when API call fails", async () => {
const onSubmit = vi.fn().mockRejectedValue(new Error("Network error"));
render(<LoginForm onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText("Email"), "[email protected]");
await userEvent.type(screen.getByLabelText("Password"), "pass123");
await userEvent.click(screen.getByRole("button", { name: "Sign in" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Network error");
});
});
describe("LoginForm", () => {
it("should handle empty form submission", async () => {
render(<LoginForm onSubmit={vi.fn()} />);
await userEvent.click(screen.getByRole("button", { name: "Sign in" }));
expect(screen.getByText("Email is required")).toBeInTheDocument();
expect(screen.getByText("Password is required")).toBeInTheDocument();
});
it("should accept max-length email (254 chars)", async () => {
render(<LoginForm onSubmit={vi.fn()} />);
const longEmail = "a".repeat(245) + "@test.com";
await userEvent.type(screen.getByLabelText("Email"), longEmail);
expect(screen.getByLabelText("Email")).toHaveValue(longEmail);
});
it("should disable submit button while request is in-flight", async () => {
const onSubmit = vi.fn().mockImplementation(() => new Promise(() => {}));
render(<LoginForm onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText("Email"), "[email protected]");
await userEvent.type(screen.getByLabelText("Password"), "pass123");
await userEvent.click(screen.getByRole("button", { name: "Sign in" }));
expect(screen.getByRole("button", { name: "Sign in" })).toBeDisabled();
});
});
describe("LoginForm — security", () => {
it("should not render XSS payload from error message", async () => {
const onSubmit = vi.fn().mockRejectedValue(
new Error('<img src=x onerror=alert(1)>')
);
render(<LoginForm onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText("Email"), "[email protected]");
await userEvent.type(screen.getByLabelText("Password"), "pass123");
await userEvent.click(screen.getByRole("button", { name: "Sign in" }));
const alert = await screen.findByRole("alert");
expect(alert.innerHTML).not.toContain("<img");
expect(alert.innerHTML).not.toContain("onerror");
});
it("should not expose password in the DOM after submission", async () => {
render(<LoginForm onSubmit={vi.fn()} />);
await userEvent.type(screen.getByLabelText("Password"), "secret123");
expect(screen.getByLabelText("Password")).toHaveAttribute("type", "password");
});
});
describe("ProtectedRoute — security", () => {
it("should redirect unauthenticated users to login", () => {
render(
<AuthContext.Provider value={{ isAuthenticated: false }}>
<ProtectedRoute><Dashboard /></ProtectedRoute>
</AuthContext.Provider>
);
expect(screen.queryByText("Dashboard")).not.toBeInTheDocument();
});
});
What SKILL.md sets; muted values are Claude Code's defaults
7 skills in this plugin
/react-componentsReact component patterns for building robust, composable UI — function components, hooks rules, Server vs Client Components, composition strategies, props design, and performance optimizations./react-data-fetchingData fetching patterns for React and Next.js — Server Components, Server Actions, SWR, TanStack Query, loading/error handling, and revalidation strategies./react-project-structureNext.js App Router project layout conventions — directory structure, co-location, feature-based organisation, shared components, hooks, utilities, monorepo patterns with Turborepo./react-routingRouting patterns for Next.js App Router (file-based routing, layouts, middleware, parallel/intercepting routes) and React Router v6+ (createBrowserRouter, loaders, actions, nested routes)./react-stateReact state management patterns — useState, useReducer, useContext, Zustand, and Redux Toolkit with a decision tree for choosing the right solution./react-stylingReact styling approaches — Prismatic React (org default), Material UI, Tailwind CSS, CSS Modules, Bootstrap, conditional class utilities, responsive design, and theming/dark mode.npx claudepluginhub gagandeepp/software-agent-teams --plugin frontend-react