서버 컴포넌트 모킹 및 테스트
데이터 계층과 네트워크 호출을 모킹해 비동기 서버 컴포넌트, 서버 액션, 경로 처리기를 테스트하고, 전체 스택 Next.js 테스트를 빠르고 안정적으로 유지합니다.
서버 컴포넌트 모킹 및 테스트은(는) CoddyKit의 무료 Next.js 15 Fullstack Web Apps 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack Web Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
자주 묻는 질문
“서버 컴포넌트 모킹 및 테스트” 강의는 무료인가요?
네 — “서버 컴포넌트 모킹 및 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack Web Apps 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“서버 컴포넌트 모킹 및 테스트”에서 뭘 배우나요?
데이터 계층과 네트워크 호출을 모킹해 비동기 서버 컴포넌트, 서버 액션, 경로 처리기를 테스트하고, 전체 스택 Next.js 테스트를 빠르고 안정적으로 유지합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack Web Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack Web Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack Web Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“서버 컴포넌트 모킹 및 테스트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack Web Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack Web Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 단위 및 통합 테스트
- Playwright를 사용한 종단 간 테스트
- 모노레포와 마이크로 프런트엔드
- 서버 컴포넌트 모킹 및 테스트