Course contentsShow
← React
Lesson 2184 of 2,39648. End-to-End TestingFree lesson

Unit Tests for Component Logic

Test isolated component behavior, conditional rendering, event handlers, and state changes with RTL unit tests.

Unit Tests for Component Logic

What you'll learn: How to write focused unit tests that verify a single component's behavior in isolation—testing its rendering logic, event handlers, state changes, and conditional outputs.

The Unit Test Mission

Unit tests sit at the base of the testing pyramid. Their job is to test one component at a time, validating that it handles props correctly, responds to user interactions, manages internal state, and renders the right output under different conditions. Think of them as quality checks for individual building blocks before you assemble the whole structure.

What Unit Tests Should Cover

Rendering based on props: Does your component show different content when you pass isLoading={true} vs isLoading={false}? Test both scenarios.

Conditional rendering logic: If a UserProfile should only show an "Edit" button when isOwner={true}, verify that button appears in one case and is absent in the other.

Event handler behavior: When a user clicks a button, does the onClick handler fire? Does it call the correct callback prop? Use userEvent.click() and verify the expected function was invoked or state changed.

State changes and their effects: If clicking a toggle button should show/hide a panel, test that the panel appears after the click. You're not testing the internal useState call—you're testing the result that the user sees.

The Isolation Principle

Unit tests work best when you test components independently. Use RTL's render() to mount just the component you're testing. Pass mock functions for callbacks. For data fetching, use MSW to control API responses. This isolation means tests run fast and failures pinpoint exactly which component broke.

Key Takeaway: Unit tests verify isolated component behavior—how props affect rendering, how events trigger changes, and how state updates manifest in the UI—giving you fast, focused feedback on individual building blocks.