Mocking y pruebas de componentes del servidor
Pruebe componentes asíncronos del servidor, Server Actions y gestores de rutas simulando las capas de datos y las llamadas de red para que sus pruebas fullstack de Next.js sean rápidas y fiables.
Mocking y pruebas de componentes del servidor es una lección gratuita de Next.js 15 Fullstack Web Apps 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 Web Apps, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Next.js 15 Fullstack Web Apps incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Server Component Challenge
Server Components are async and run on the server, so classic client-render test tools do not fit perfectly. The key is to test their data dependencies in isolation and test the rendered output separately.
Separate Logic from Rendering
Extract data-fetching and business logic into plain functions. Pure functions are trivial to unit test without rendering anything.
export function formatPrice(cents) {
return '$' + (cents / 100).toFixed(2);
}Testing a Pure Helper
A pure helper is testable anywhere with no mocks at all.
function formatPrice(cents) {
return '$' + (cents / 100).toFixed(2);
}
console.log(formatPrice(1999) === '$19.99');
console.log(formatPrice(500) === '$5.00');Mocking the Data Layer
Server Components usually call a repository or ORM. Mock that module so tests do not hit a real database.
import { vi } from 'vitest';
import * as db from '@/lib/db';
vi.spyOn(db, 'getUser').mockResolvedValue({ id: 1, name: 'Ada' });Rendering an Async Server Component
Because the component is async, you can await it to get its element tree, then assert on it with your render utility.
import { render, screen } from '@testing-library/react';
import Profile from '@/app/profile/page';
it('shows the name', async () => {
render(await Profile());
expect(screen.getByText('Ada')).toBeInTheDocument();
});Mocking fetch with MSW
When a component fetches from an external API, intercept the request with Mock Service Worker (MSW) instead of stubbing fetch by hand.
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('https://api.example.com/user', () =>
HttpResponse.json({ name: 'Ada' })
),
];Testing Server Actions
Server Actions are async functions. Call them directly with mocked dependencies and assert on side effects and return values.
import { createTodo } from '@/app/actions';
import * as db from '@/lib/db';
it('creates a todo', async () => {
const spy = vi.spyOn(db, 'insertTodo').mockResolvedValue({ id: 1 });
await createTodo('Write tests');
expect(spy).toHaveBeenCalledWith('Write tests');
});Mocking revalidatePath
Actions often call revalidatePath. Mock next/cache so the call does not throw outside a request scope, and assert it was invoked.
vi.mock('next/cache', () => ({
revalidatePath: vi.fn(),
}));Testing Route Handlers
Route handlers take a Request and return a Response. Build a request, call the handler, and inspect the response.
import { POST } from '@/app/api/todos/route';
it('returns 400 on empty body', async () => {
const req = new Request('http://t/api/todos', { method: 'POST', body: '{}' });
const res = await POST(req);
expect(res.status).toBe(400);
});Keep Tests Deterministic
Avoid flaky tests:
- Reset mocks between tests (
vi.clearAllMocks()). - Freeze time when testing dates.
- Never call real networks or databases.
The Testing Pyramid
Balance your suite: many fast unit tests for logic, fewer integration tests for components plus data, and a small set of E2E tests (Playwright) for critical flows.
Quick Check
What is the recommended way to test an async Server Component that calls your ORM?
Recap
You learned to test fullstack Next.js code:
- Separate pure logic for easy unit tests.
- Mock the data layer and use MSW for network calls.
- Await async Server Components; call Server Actions and route handlers directly.
- Keep tests deterministic and follow the testing pyramid.
Preguntas frecuentes
¿La lección «Mocking y pruebas de componentes del servidor» es gratis?
Sí — el texto completo de «Mocking y pruebas de componentes del servidor» 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 Web Apps, actualiza a CoddyKit PRO. El curso de Next.js 15 Fullstack Web Apps incluye 4 lecciones en total.
¿Qué aprenderé en «Mocking y pruebas de componentes del servidor»?
Pruebe componentes asíncronos del servidor, Server Actions y gestores de rutas simulando las capas de datos y las llamadas de red para que sus pruebas fullstack de Next.js sean rápidas y fiables. Practicas Next.js 15 Fullstack Web Apps 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 Web Apps?
No se requiere experiencia previa. Next.js 15 Fullstack Web Apps 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 «Mocking y pruebas de componentes del servidor»?
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 Web Apps?
Sí. Cada lección de Next.js 15 Fullstack Web Apps 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
- Pruebas unitarias y de integración
- Pruebas de extremo a extremo con Playwright
- Monorepos y microfrontends
- Mocking y pruebas de componentes del servidor