0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Ders

Bileşenleri Birim Sınamasından Geçirme

React bileşenleriniz için React Testing Library ve Jest gibi sınama kitaplıklarını kullanarak etkili birim sınamaları yazın.

Bileşenleri Birim Sınamasından Geçirme, CoddyKit'te ücretsiz bir Next.js 15 Fullstack (App Router + Server Actions) dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Next.js 15 Fullstack (App Router + Server Actions) öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Next.js 15 Fullstack (App Router + Server Actions) kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Intro to Unit Testing

Welcome to unit testing for React components! Unit testing helps ensure that the smallest, independent parts of your code — your components — work exactly as intended.

  • What is a unit test? It's a test for a 'unit' of code, often a single function or component.
  • Why test components? To catch bugs early, prevent regressions, and ensure your UI behaves predictably.
  • We'll focus on isolating components and testing their specific functionality.

Jest: The Test Runner

Jest is a popular JavaScript testing framework developed by Facebook. It's often used with React because it's fast, feature-rich, and includes everything you need for testing.

  • Test Runner: Executes your tests and reports results.
  • Assertion Library: Provides functions like expect to check if values meet certain conditions.
  • Mocking Library: Helps isolate code by replacing dependencies with 'mock' versions.

React Testing Library (RTL)

While Jest runs the tests, React Testing Library (RTL) helps you test React components in a way that mimics how users interact with them.

  • User-centric: RTL encourages testing actual user behavior, not internal implementation details.
  • Accessibility: Its querying methods (like getByRole) promote good accessibility practices.
  • It provides utilities to render components, query the DOM, and simulate user events.

Setting Up Your Test Environment

Next.js projects often come with Jest and RTL already configured or easily added. Here's what you'll typically use:

  • jest: The core test runner.
  • @testing-library/react: The main library for testing React components.
  • @testing-library/jest-dom: Provides custom Jest matchers for better DOM assertions (e.g., .toBeInTheDocument()).

These libraries work together to create a powerful testing setup.

Our First Component to Test

Let's create a simple MyButton component. It will display some text and execute a function when clicked. This is a common pattern for interactive UI elements.

We'll save this as components/MyButton.js:

import React from 'react';

function MyButton({ text, onClick }) {
  return (
    <button onClick={onClick}>
      {text}
    </button>
  );
}

export default MyButton;

Basic Test Structure & Render

Test files typically live alongside the component (e.g., components/MyButton.test.js). We use describe to group related tests and test (or it) for individual test cases.

First, let's just render our button and ensure it appears. We'll use render from RTL.

import { render, screen } from '@testing-library/react';
import MyButton from './MyButton';

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

Querying Elements with RTL

RTL provides various 'query' methods to find elements in the rendered component. It's best to use queries that resemble how a user would find elements, prioritizing accessibility.

  • getByRole: Finds elements by their ARIA role (e.g., 'button', 'heading'). Highly recommended!
  • getByText: Finds elements containing specific text.
  • getByLabelText: Finds elements associated with a label.

We used getByText in the previous example, which is great for text content.

Simulating Interaction & Assertions

Now, let's test if our button's onClick handler is called when clicked. We use fireEvent from RTL to simulate user events and jest.fn() to create a 'mock' function.

jest.fn() lets us track if the function was called, how many times, and with what arguments. .toHaveBeenCalledTimes() is a jest-dom matcher.

import { render, screen, fireEvent } from '@testing-library/react';
import MyButton from './MyButton';

describe('MyButton', () => {
  test('calls onClick handler when clicked', () => {
    const handleClick = jest.fn(); // Create a mock function
    render(<MyButton text="Submit" onClick={handleClick} />);
    
    const buttonElement = screen.getByRole('button', { name: /Submit/i });
    fireEvent.click(buttonElement); // Simulate a click
    
    expect(handleClick).toHaveBeenCalledTimes(1); // Assert it was called once
  });
});

Quick Check on Testing

You have a component called Greeting that displays 'Hello, [name]!'.

// components/Greeting.js

function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}
export default Greeting;

Which test snippet correctly asserts that 'Hello, Alice!' is rendered?

Recap: Unit Testing Components

Great job! You've taken your first steps into unit testing React components using Jest and React Testing Library.

  • Jest is your test runner and assertion framework.
  • React Testing Library helps you test components from a user's perspective.
  • You learned to render components, query for elements, simulate user interactions, and make assertions about component behavior.

Keep practicing to build robust and reliable Next.js applications!

Sıkça Sorulan Sorular

“Bileşenleri Birim Sınamasından Geçirme” dersi ücretsiz mi?

Evet — “Bileşenleri Birim Sınamasından Geçirme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Next.js 15 Fullstack (App Router + Server Actions) kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Next.js 15 Fullstack (App Router + Server Actions) kursu toplamda 4 dersten oluşur.

“Bileşenleri Birim Sınamasından Geçirme” dersinde ne öğreneceğim?

React bileşenleriniz için React Testing Library ve Jest gibi sınama kitaplıklarını kullanarak etkili birim sınamaları yazın. Next.js 15 Fullstack (App Router + Server Actions) ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Next.js 15 Fullstack (App Router + Server Actions) öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Next.js 15 Fullstack (App Router + Server Actions), başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“Bileşenleri Birim Sınamasından Geçirme” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Next.js 15 Fullstack (App Router + Server Actions) dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Next.js 15 Fullstack (App Router + Server Actions) dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Bileşenleri Birim Sınamasından Geçirme
  2. Sayfaları Tümleştirme Sınamasından Geçirme
  3. Playwright/Cypress ile Uçtan Uca Test
  4. API Rotalarını Taklit Etme ve Test Etme
← Next.js 15 Fullstack (App Router + Server Actions) Sayfasına Dön