JS Testing Skill — Vitest + React Testing Library for Next.js
Critical Rules
- Vitest is the test runner. Do not use Jest. All configuration, mocking, and assertions use the Vitest API (
vi.fn(), vi.mock(), vi.spyOn(), etc.). - React Testing Library (RTL) for component tests. Query elements the way a user would find them — by role, label, text, or placeholder. Never reach for
getByTestId unless no semantic query is possible. - Test user behavior, not implementation. Assert what the user sees and can interact with. Do not assert on component state, refs, internal variables, or hook return values directly (except when using
renderHook). - Never test React internals. Do not mock
useState, useEffect, useRef, or any React built-in. If you need to control what a hook returns, extract the logic into a custom hook and test it with renderHook. - Use MSW for API mocking. Mock at the network layer with Mock Service Worker, not by stubbing
fetch or axios directly. This gives realistic request/response cycles and catches serialization issues. - Prefer `userEvent` over `fireEvent`.
userEvent simulates real browser behavior (focus, blur, keystrokes). fireEvent dispatches synthetic DOM events and should only be used for events userEvent does not support. - Every test file must be self-contained. Shared setup belongs in
vitest.setup.ts or a dedicated test utility file, not scattered across tests via implicit globals.
Component Testing
Basic Render Test
tsx
// components/greeting.tsx
export function Greeting({ name }: { name: string }) {
return <h1>Hello, {name}!</h1>;
}
tsx
// components/greeting.test.tsx
import { render, screen } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { Greeting } from "./greeting";
describe("Greeting", () => {
it("renders the user name", () => {
render(<Greeting name="Kelley" />);
expect(
screen.getByRole("heading", { name: /hello, kelley/i })
).toBeInTheDocument();
});
});
User Interaction Test (Click)
tsx
// components/counter.tsx
"use client";
import { useState } from "react";
export function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
</div>
);
}
tsx
// components/counter.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect } from "vitest";
import { Counter } from "./counter";
describe("Counter", () => {
it("increments the count when the button is clicked", async () => {
const user = userEvent.setup();
render(<Counter />);
expect(screen.getByText("Count: 0")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: /increment/i }));
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
});
User Interaction Test (Typing)
tsx
// components/search-input.tsx
"use client";
import { useState } from "react";
export function SearchInput({ onSearch }: { onSearch: (query: string) => void }) {
const [query, setQuery] = useState("");
return (
<form
onSubmit={(e) => {
e.preventDefault();
onSearch(query);
}}
>
<label htmlFor="search">Search</label>
<input
id="search"
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button type="submit">Go</button>
</form>
);
}
tsx
// components/search-input.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi } from "vitest";
import { SearchInput } from "./search-input";
describe("SearchInput", () => {
it("calls onSearch with the typed query on submit", async () => {
const user = userEvent.setup();
const handleSearch = vi.fn();
render(<SearchInput onSearch={handleSearch} />);
await user.type(screen.getByLabelText(/search/i), "vitest");
await user.click(screen.getByRole("button", { name: /go/i }));
expect(handleSearch).toHaveBeenCalledWith("vitest");
expect(handleSearch).toHaveBeenCalledTimes(1);
});
});
Async Data Loading Test
tsx
// components/user-profile.tsx
"use client";
import { useEffect, useState } from "react";
interface User {
id: number;
name: string;
email: string;
}
export function UserProfile({ userId }: { userId: number }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => {
setUser(data);
setLoading(false);
});
}, [userId]);
if (loading) return <p>Loading profile...</p>;
if (!user) return <p>User not found</p>;
return (
<article>
<h2>{user.name}</h2>
<p>{user.email}</p>
</article>
);
}
tsx
// components/user-profile.test.tsx
import { render, screen } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { http, HttpResponse } from "msw";
import { server } from "@/test/msw-server";
import { UserProfile } from "./user-profile";
describe("UserProfile", () => {
it("shows loading state then renders user data", async () => {
server.use(
http.get("/api/users/1", () => {
return HttpResponse.json({
id: 1,
name: "Kelley",
email: "kelley@example.com",
});
})
);
render(<UserProfile userId={1} />);
expect(screen.getByText(/loading profile/i)).toBeInTheDocument();
expect(
await screen.findByRole("heading", { name: /kelley/i })
).toBeInTheDocument();
expect(screen.getByText("kelley@example.com")).toBeInTheDocument();
});
});
Form Submission Test
tsx
// components/contact-form.tsx
"use client";
import { useState } from "react";
export function ContactForm() {
const [submitted, setSubmitted] = useState(false);
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const res = await fetch("/api/contact", {
method: "POST",
body: JSON.stringify({
name: formData.get("name"),
message: formData.get("message"),
}),
headers: { "Content-Type": "application/json" },
});
if (res.ok) setSubmitted(true);
}
if (submitted) return <p>Thank you for your message!</p>;
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input id="name" name="name" required />
<label htmlFor="message">Message</label>
<textarea id="message" name="message" required />
<button type="submit">Send</button>
</form>
);
}
tsx
// components/contact-form.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect } from "vitest";
import { http, HttpResponse } from "msw";
import { server } from "@/test/msw-server";
import { ContactForm } from "./contact-form";
describe("ContactForm", () => {
it("submits the form and shows a success message", async () => {
const user = userEvent.setup();
server.use(
http.post("/api/contact", () => {
return HttpResponse.json({ success: true });
})
);
render(<ContactForm />);
await user.type(screen.getByLabelText(/name/i), "Kelley");
await user.type(screen.getByLabelText(/message/i), "Hello there");
await user.click(screen.getByRole("button", { name: /send/i }));
expect(
await screen.findByText(/thank you for your message/i)
).toBeInTheDocument();
});
});
Error State Test
tsx
// components/contact-form.test.tsx (additional test)
describe("ContactForm", () => {
// ... success test above ...
it("shows an error message when submission fails", async () => {
const user = userEvent.setup();
server.use(
http.post("/api/contact", () => {
return HttpResponse.json(
{ error: "Server error" },
{ status: 500 }
);
})
);
render(<ContactForm />);
await user.type(screen.getByLabelText(/name/i), "Kelley");
await user.type(screen.getByLabelText(/message/i), "Hello");
await user.click(screen.getByRole("button", { name: /send/i }));
// The form should still be visible (not replaced by success message)
expect(
await screen.findByText(/something went wrong/i)
).toBeInTheDocument();
expect(screen.getByRole("button", { name: /send/i })).toBeInTheDocument();
});
});
API Route Testing (Next.js App Router)
Testing a GET Route Handler
ts
// app/api/users/route.ts
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const role = searchParams.get("role");
const users = role
? await db.user.findMany({ where: { role } })
: await db.user.findMany();
return NextResponse.json(users);
}
ts
// app/api/users/route.test.ts
import { describe, it, expect, vi, beforeEach } from "vitest";
import { GET } from "./route";
vi.mock("@/lib/db", () => ({
db: {
user: {
findMany: vi.fn(),
},
},
}));
import { db } from "@/lib/db";
const mockFindMany = vi.mocked(db.user.findMany);
describe("GET /api/users", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("returns all users when no role filter is provided", async () => {
const users = [
{ id: 1, name: "Alice", role: "admin" },
{ id: 2, name: "Bob", role: "user" },
];
mockFindMany.mockResolvedValue(users);
const request = new Request("http://localhost/api/users");
const response = await GET(request);
const data = await response.json();
expect(response.status).toBe(200);
expect(data).toEqual(users);
expect(mockFindMany).toHaveBeenCalledWith();
});
it("filters users by role when query param is provided", async () => {
const admins = [{ id: 1, name: "Alice", role: "admin" }];
mockFindMany.mockResolvedValue(admins);
const request = new Request("http://localhost/api/users?role=admin");
const response = await GET(request);
const data = await response.json();
expect(data).toEqual(admins);
expect(mockFindMany).toHaveBeenCalledWith({ where: { role: "admin" } });
});
});
Testing a POST Route Handler
ts
// app/api/posts/route.ts
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { getServerSession } from "@/lib/auth";
export async function POST(request: Request) {
const session = await getServerSession();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const body = await request.json();
if (!body.title || !body.content) {
return NextResponse.json(
{ error: "Title and content are required" },
{ status: 400 }
);
}
const post = await db.post.create({
data: {
title: body.title,
content: body.content,
authorId: session.user.id,
},
});
return NextResponse.json(post, { status: 201 });
}
ts
// app/api/posts/route.test.ts
import { describe, it, expect, vi, beforeEach } from "vitest";
import { POST } from "./route";
vi.mock("@/lib/db", () => ({
db: {
post: {
create: vi.fn(),
},
},
}));
vi.mock("@/lib/auth", () => ({
getServerSession: vi.fn(),
}));
import { db } from "@/lib/db";
import { getServerSession } from "@/lib/auth";
const mockCreate = vi.mocked(db.post.create);
const mockGetSession = vi.mocked(getServerSession);