Simulação e Testes de Rotas de API
Teste os Manipuladores de Rotas e as Ações de Servidor do Next.js isoladamente, simulando o banco de dados, chamadas de rede e serviços externos com Jest e MSW.
Simulação e Testes de Rotas de API é uma aula grátis de Next.js 15 Fullstack (App Router + Server Actions) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Next.js 15 Fullstack (App Router + Server Actions), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Next.js 15 Fullstack (App Router + Server Actions) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Perguntas Frequentes
A aula “Simulação e Testes de Rotas de API” é grátis?
Sim — o texto completo de “Simulação e Testes de Rotas de API” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Next.js 15 Fullstack (App Router + Server Actions), atualize para CoddyKit PRO. O curso de Next.js 15 Fullstack (App Router + Server Actions) inclui 4 aulas no total.
O que vou aprender em “Simulação e Testes de Rotas de API”?
Teste os Manipuladores de Rotas e as Ações de Servidor do Next.js isoladamente, simulando o banco de dados, chamadas de rede e serviços externos com Jest e MSW. Você pratica Next.js 15 Fullstack (App Router + Server Actions) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Next.js 15 Fullstack (App Router + Server Actions)?
Nenhuma experiência prévia é necessária. Next.js 15 Fullstack (App Router + Server Actions) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Simulação e Testes de Rotas de API”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Next.js 15 Fullstack (App Router + Server Actions)?
Sim. Cada aula de Next.js 15 Fullstack (App Router + Server Actions) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Testes unitários de componentes
- Testes de integração de páginas
- Testes de ponta a ponta com Playwright/Cypress
- Simulação e Testes de Rotas de API