0Pricing
Next.js 15 Fullstack Web Apps · 강의

단위 및 통합 테스트

Jest와 React Testing Library를 사용하여 React 구성 요소와 Next.js 함수에 대한 효과적인 단위 테스트와 통합 테스트를 작성합니다.

단위 및 통합 테스트은(는) CoddyKit의 무료 Next.js 15 Fullstack Web Apps 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack Web Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why We Test Our Code

Welcome! In modern web development, especially with complex applications built with Next.js, ensuring your code works as expected is crucial. This is where testing comes in.

  • Reliability: Tests prevent bugs and regressions.
  • Maintainability: Well-tested code is easier to refactor and update.
  • Confidence: You can deploy new features with greater assurance.

We'll focus on Unit Tests (small, isolated parts) and Integration Tests (how parts work together).

Setting Up Jest & RTL

Jest is a popular JavaScript testing framework, and React Testing Library (RTL) is a set of utilities for testing React components. Together, they form a powerful duo for Next.js apps.

First, install the necessary packages:

npm install --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom

Your First Unit Test (Function)

A unit test checks a small, isolated piece of code, like a single function. Let's create a simple utility function and then write a test for it.

Here's our utility:

// utils/math.js
function add(a, b) {
  return a + b;
}

// This block makes the file directly runnable via Node.js
if (typeof require !== 'undefined' && require.main === module) {
  console.log("Running add(5, 3):", add(5, 3)); // Expected: 8
  console.log("Running add(10, -2):", add(10, -2)); // Expected: 8
}

Testing the 'add' Function

Now, let's write a test for our add function. Jest uses describe to group tests and test (or it) for individual test cases. expect is used for assertions.

Save this in utils/math.test.js:

// utils/math.test.js
import { add } from './math';

describe('add function', () => {
  test('should correctly add two positive numbers', () => {
    expect(add(1, 2)).toBe(3);
  });

  test('should handle negative numbers', () => {
    expect(add(5, -3)).toBe(2);
  });
});

// To run tests: npx jest

Introducing React Testing Library

React Testing Library (RTL) encourages testing components in a way that mimics how users interact with them. Instead of checking internal state, you query the DOM for elements a user would see or interact with.

  • render: Mounts a React component into a virtual DOM.
  • screen: Provides methods to query the rendered DOM (e.g., getByText, getByRole).
  • @testing-library/jest-dom: Adds custom matchers like toBeInTheDocument.

Testing a Simple React Component

Let's test a basic button component. We'll ensure it renders with the correct text.

First, the component (components/Button.jsx):

// components/Button.jsx
export default function Button({ label, onClick }) {
  return (
    <button onClick={onClick}>
      {label}
    </button>
  );
}

Testing Component Rendering

Now, the test for our Button component. We use render to put it on the screen and screen.getByText to find it, then toBeInTheDocument to confirm its presence.

Save this as components/Button.test.jsx:

// components/Button.test.jsx
import { render, screen } from '@testing-library/react';
import Button from './Button';

describe('Button component', () => {
  test('renders with the correct label', () => {
    render(<Button label="Click Me" />);
    const buttonElement = screen.getByText(/Click Me/i);
    expect(buttonElement).toBeInTheDocument();
  });
});

Simulating User Interactions

Beyond just rendering, we need to test how components respond to user actions. RTL's fireEvent (or userEvent for more realistic interactions) helps simulate clicks, input changes, etc.

We can check if a function passed via props is called.

// components/Button.test.jsx (continued)
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';

describe('Button component interactions', () => {
  test('calls the onClick handler when clicked', () => {
    const handleClick = jest.fn(); // Jest mock function
    render(<Button label="Click Me" onClick={handleClick} />);
    const buttonElement = screen.getByText(/Click Me/i);
    fireEvent.click(buttonElement);
    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});

Integration: Testing Route Handlers

Next.js Route Handlers (API routes in the App Router) are server-side functions. We can test them by directly importing and calling their HTTP methods (like GET, POST) and mocking Next.js's request/response objects.

Here's an example:

// app/api/hello/route.js
import { NextResponse } from 'next/server';

export async function GET() {
  return NextResponse.json({ message: 'Hello from API!' }, { status: 200 });
}

// app/api/hello/route.test.js
import { GET } from './route';

describe('GET /api/hello', () => {
  test('should return a greeting message with status 200', async () => {
    // No need to mock NextRequest/NextResponse directly for simple cases
    // as NextResponse.json returns a standard Response object.
    const response = await GET();
    const json = await response.json();

    expect(response.status).toBe(200);
    expect(json.message).toBe('Hello from API!');
  });
});

Best Practices for Effective Tests

To write useful and maintainable tests:

  • Test user behavior: Focus on what the user sees and does, not internal component state.
  • Keep tests focused: Each test should ideally check one thing.
  • Make tests fast: Slow tests discourage running them often.
  • Readability: Write clear tests that are easy to understand.
  • Mock dependencies: Use jest.mock() or jest.fn() to isolate units and prevent external factors from affecting tests.

Quick Check

Which of the following statements about testing in Next.js with Jest and React Testing Library is TRUE?

Recap: Unit & Integration Testing

Great job! You've learned the fundamentals of unit and integration testing in Next.js:

  • Jest is your testing framework.
  • React Testing Library helps test components like a user would.
  • Unit tests verify small, isolated code units.
  • Integration tests check how different parts (like components and APIs) work together.
  • You can test functions, React components, and Next.js Route Handlers.
  • Best practices include focusing on user behavior and mocking dependencies.

Next up, we'll explore End-to-End testing for full application flows!

자주 묻는 질문

“단위 및 통합 테스트” 강의는 무료인가요?

네 — “단위 및 통합 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack Web Apps 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“단위 및 통합 테스트”에서 뭘 배우나요?

Jest와 React Testing Library를 사용하여 React 구성 요소와 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개 중 1번째 강의입니다.

“단위 및 통합 테스트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Next.js 15 Fullstack Web Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Next.js 15 Fullstack Web Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 단위 및 통합 테스트
  2. Playwright를 사용한 종단 간 테스트
  3. 모노레포와 마이크로 프런트엔드
  4. 서버 컴포넌트 모킹 및 테스트
← Next.js 15 Fullstack Web Apps(으)로 돌아가기