페이지 통합 테스트
애플리케이션의 여러 부분이 함께 제대로 작동하는지 확인하기 위해 Next.js 페이지와 API 경로에 대한 통합 테스트를 수행합니다.
페이지 통합 테스트은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack (App Router + Server Actions) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to Integration Tests
Welcome! In this lesson, we'll explore integration testing for your Next.js applications.
Integration tests verify that different parts of your application work correctly together. Instead of isolated units, we check the flow between components, pages, and API routes.
Why Test Pages & Routes?
For Next.js, integration testing is crucial because it ensures:
- Pages render correctly with their data.
- User interactions (like form submissions) trigger the right backend logic.
- API routes respond as expected when called from the frontend or other services.
It helps catch issues that unit tests might miss when components interact.
Tools: Jest, RTL, next/test-utils
We'll primarily use these tools for integration testing:
- Jest: A popular JavaScript testing framework.
- React Testing Library (RTL): For rendering React components (like your Next.js pages) and simulating user interactions.
@next/test-utils: Provides helpers specifically for testing Next.js features, like API routes.
Testing a Page Component
To test a Next.js page component, we can render it using React Testing Library. This allows us to assert if the correct content is displayed and interact with elements on the page.
You'll typically import the page component directly and render it in your test file.
Code: Simple Page Test
Here's how you might test a simple About page to ensure its heading is rendered.
// pages/about.js
export default function About() {
return (
<div>
<h1>About Us</h1>
<p>This is the about page.</p>
</div>
);
}
// __tests__/about.test.js
import { render, screen } from '@testing-library/react';
import About from '../pages/about';
describe('About Page', () => {
it('renders the about page heading', () => {
render(<About />);
const heading = screen.getByRole('heading', { name: /About Us/i });
expect(heading).toBeInTheDocument();
});
});User Interaction in Tests
Integration tests often involve simulating user behavior. React Testing Library provides utilities like fireEvent (or userEvent for more realistic interactions) to click buttons, type into inputs, and more.
This lets you verify that your page responds correctly to user input, just like a real user would.
// components/Counter.js
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// __tests__/counter.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from '../components/Counter';
describe('Counter Component', () => {
it('increments count on button click', () => {
render(<Counter />);
const button = screen.getByRole('button', { name: /Increment/i });
fireEvent.click(button);
expect(screen.getByText(/Count: 1/i)).toBeInTheDocument();
});
});Testing Next.js API Routes
Next.js API routes are server-side functions. You can test them by importing their handler function and using createNextApiHandler from @next/test-utils to simulate requests.
This allows you to send mock requests and assert the status code and JSON response.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' });
}
// __tests__/api/hello.test.js
import { createNextApiHandler } from '@next/test-utils';
import handler from '../../pages/api/hello';
describe('/api/hello', () => {
it('returns a name', async () => {
const testHandler = createNextApiHandler(handler);
const res = await testHandler({ method: 'GET' });
expect(res.statusCode).toBe(200);
expect(await res.json()).toEqual({ name: 'John Doe' });
});
});Mocking External Calls in API
API routes often interact with databases or other external services. In integration tests, you should mock these external dependencies to ensure your tests are fast and predictable.
Jest's mocking capabilities are perfect for this, allowing you to control the return values of these external calls.
// lib/db.js (simplified)
export const getUser = async (id) => ({ id, name: 'Mock User' });
// pages/api/user/[id].js
import { getUser } from '../../../lib/db';
export default async function handler(req, res) {
const { id } = req.query;
const user = await getUser(id);
res.status(200).json(user);
}
// __tests__/api/user.test.js
import { createNextApiHandler } from '@next/test-utils';
import handler from '../../pages/api/user/[id]';
import * as db from '../../lib/db';
describe('/api/user/[id]', () => {
it('returns a user with mocked DB', async () => {
jest.spyOn(db, 'getUser').mockResolvedValue({ id: '1', name: 'Test User' });
const testHandler = createNextApiHandler(handler);
const res = await testHandler({ method: 'GET', query: { id: '1' } });
expect(res.statusCode).toBe(200);
expect(await res.json()).toEqual({ id: '1', name: 'Test User' });
jest.restoreAllMocks();
});
});Pages & Server Actions Integration
Testing pages that use Server Actions involves rendering the page, simulating a form submission, and asserting that the Server Action was called with the correct data.
You can mock the Server Action function itself to control its return value and verify it was invoked.
// app/actions.js
'use server';
export async function submitForm(formData) {
const name = formData.get('name');
return { success: true, message: `Hello, ${name}!` };
}
// app/page.js
import { submitForm } from './actions';
export default function Page() {
return (
<form action={submitForm}>
<input type="text" name="name" defaultValue="Guest" />
<button type="submit">Say Hello</button>
</form>
);
}
// __tests__/page.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import Page from '../app/page';
import * as actions from '../app/actions';
describe('Home Page with Server Action', () => {
it('submits form and calls server action', async () => {
const mockSubmitForm = jest.spyOn(actions, 'submitForm')
.mockResolvedValue({ success: true, message: 'Hello, Test User!' });
render(<Page />);
const input = screen.getByRole('textbox', { name: /name/i });
fireEvent.change(input, { target: { value: 'Test User' } });
const button = screen.getByRole('button', { name: /Say Hello/i });
fireEvent.click(button);
expect(mockSubmitForm).toHaveBeenCalledWith(
expect.any(FormData)
);
mockSubmitForm.mockRestore();
});
});Test Your Knowledge
Time for a quick check on integration testing!
Recap: Building Robust Apps
Great job! You've learned the fundamentals of integration testing in Next.js.
- We covered how to test pages and API routes.
- You saw how to simulate user interactions and mock external dependencies.
- Tools like Jest, React Testing Library, and
@next/test-utilsare essential.
By writing integration tests, you build more robust applications and catch bugs earlier in the development process!
자주 묻는 질문
“페이지 통합 테스트” 강의는 무료인가요?
네 — “페이지 통합 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.
“페이지 통합 테스트”에서 뭘 배우나요?
애플리케이션의 여러 부분이 함께 제대로 작동하는지 확인하기 위해 Next.js 페이지와 API 경로에 대한 통합 테스트를 수행합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“페이지 통합 테스트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.