Mocking & Testing API Routes
Test Next.js Route Handlers and Server Actions in isolation by mocking the database, network calls, and external services with Jest and MSW.
Mocking & Testing API Routes is a free Next.js 15 Fullstack (App Router + Server Actions) lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Next.js 15 Fullstack (App Router + Server Actions) learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Mock?
Tests should be fast, deterministic, and isolated. Mocking replaces slow or external dependencies — databases, payment APIs, email senders — with controllable stand-ins so a single failure does not break unrelated tests.
What to Mock
Good mock targets in a Next.js app:
- The database client (Prisma)
- External HTTP calls (Stripe, OpenAI)
- Auth/session helpers
Keep the route's own logic real so you actually test it.
A Simple Route Handler
Here is a route we want to test. It reads a query param and returns JSON.
// app/api/user/route.ts
import { prisma } from '@/lib/prisma';
export async function GET(req: Request) {
const users = await prisma.user.findMany();
return Response.json(users);
}Mocking Prisma with Jest
jest.mock replaces a module. Mock the Prisma module so calls return fixed data instead of hitting a real database.
jest.mock('@/lib/prisma', () => ({
prisma: {
user: { findMany: jest.fn() }
}
}));Setting Return Values
In each test, tell the mock what to resolve with using mockResolvedValue. This drives the route down a specific path.
import { prisma } from '@/lib/prisma';
(prisma.user.findMany as jest.Mock).mockResolvedValue([
{ id: 1, name: 'Ada' }
]);Invoking the Handler
Route Handlers are plain functions. Call them directly with a Request and assert on the returned Response.
import { GET } from '@/app/api/user/route';
const res = await GET(new Request('http://test/api/user'));
const data = await res.json();
expect(data[0].name).toBe('Ada');Asserting Call Behavior
Verify the mock was used correctly with matchers like toHaveBeenCalledWith. This confirms your route passes the right arguments.
expect(prisma.user.findMany).toHaveBeenCalledTimes(1);Mocking External HTTP with MSW
For outbound calls, MSW (Mock Service Worker) intercepts requests at the network layer. Define handlers that return canned responses.
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('https://api.stripe.com/v1/charges', () =>
HttpResponse.json({ amount: 500 })
)
];Starting the Mock Server
Boot the MSW server in your test setup so every test runs against the mocked network. Reset handlers between tests for isolation.
import { setupServer } from 'msw/node';
const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());Testing Error Paths
Make mocks reject or return errors to test how your route handles failures, ensuring it returns the right status code.
(prisma.user.findMany as jest.Mock).mockRejectedValue(new Error('db down'));
const res = await GET(new Request('http://test/api/user'));
expect(res.status).toBe(500);Best Practices
Keep mocked tests trustworthy:
- Mock the edges, keep logic real
- Reset mocks between tests
- Cover success and error paths
- Use MSW for realistic network mocking
Quick Check
Test your mocking knowledge.
Recap
You learned to test routes in isolation:
- Mock the Prisma client with
jest.mockandmockResolvedValue - Call Route Handlers directly and assert on the
Response - Intercept outbound HTTP with MSW
- Cover error paths by making mocks reject
Your API tests are now fast and reliable.
Frequently asked questions
Is the “Mocking & Testing API Routes” lesson free?
Yes — the full text of “Mocking & Testing API Routes” is free to read here on the web, and the Next.js 15 Fullstack (App Router + Server Actions) course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Next.js 15 Fullstack (App Router + Server Actions) course, upgrade to CoddyKit PRO.
What will I learn in “Mocking & Testing API Routes”?
Test Next.js Route Handlers and Server Actions in isolation by mocking the database, network calls, and external services with Jest and MSW. You practise Next.js 15 Fullstack (App Router + Server Actions) with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Next.js 15 Fullstack (App Router + Server Actions)?
No prior experience is required. Next.js 15 Fullstack (App Router + Server Actions) on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Mocking & Testing API Routes” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Next.js 15 Fullstack (App Router + Server Actions) lesson?
Yes. Every Next.js 15 Fullstack (App Router + Server Actions) lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Unit Testing Components
- Integration Testing Pages
- E2E with Playwright/Cypress
- Mocking & Testing API Routes