0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Lección

Simulación y pruebas de rutas de API

Pruebe Route Handlers y Server Actions de Next.js de forma aislada simulando la base de datos, las llamadas de red y los servicios externos con Jest y MSW.

Simulación y pruebas de rutas de API es una lección gratuita de Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Next.js 15 Fullstack (App Router + Server Actions), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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.mock and mockResolvedValue
  • 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.

Preguntas frecuentes

¿La lección «Simulación y pruebas de rutas de API» es gratis?

Sí — el texto completo de «Simulación y pruebas de rutas de API» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Next.js 15 Fullstack (App Router + Server Actions), actualiza a CoddyKit PRO. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 4 lecciones en total.

¿Qué aprenderé en «Simulación y pruebas de rutas de API»?

Pruebe Route Handlers y Server Actions de Next.js de forma aislada simulando la base de datos, las llamadas de red y los servicios externos con Jest y MSW. Practicas Next.js 15 Fullstack (App Router + Server Actions) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Next.js 15 Fullstack (App Router + Server Actions)?

No se requiere experiencia previa. Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Simulación y pruebas de rutas de API»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Next.js 15 Fullstack (App Router + Server Actions)?

Sí. Cada lección de Next.js 15 Fullstack (App Router + Server Actions) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Pruebas unitarias de componentes
  2. Pruebas de integración de páginas
  3. Pruebas E2E con Playwright/Cypress
  4. Simulación y pruebas de rutas de API
← Volver a Next.js 15 Fullstack (App Router + Server Actions)