Course contentsShow
← React
Lesson 2122 of 2,39647. Testing Patterns and Best PracticesFree lesson

Refactoring Should Not Break Tests

Well-written tests survive component refactors like extracting components or changing state management libraries.

Refactoring Should Not Break Tests

You'll learn why well-designed tests survive component refactors without requiring any changes themselves.

The Promise of Good Tests

When your tests focus on user-facing behavior rather than implementation details, they become a safety net during refactoring. You should be able to extract components, rename variables, switch from useState to useReducer, or even replace your state management library — and your tests should still pass without modification.

This is the ultimate validation that you've tested the right things.

How This Works in Practice

Imagine you have a UserProfile component that fetches and displays user data. Your test verifies:

  • Loading state appears initially
  • User's name displays after fetch completes
  • Error message shows if fetch fails

Now you refactor:

  • Extract a UserAvatar sub-component
  • Move fetch logic into a custom useUserData hook
  • Switch from useState to Zustand for state management
  • Rename internal variables from userData to profile

If your tests break, they were testing implementation. If they still pass, they were testing behavior — exactly what the user experiences didn't change.

The Safety Net Analogy

Think of tests like a building inspector checking a house. A bad inspector measures the exact position of every nail and wire. When you remodel a room, they fail you even though the house still works perfectly. A good inspector checks: "Do the lights turn on? Is the water safe? Are exits accessible?" Remodel all you want — if those things still work, you pass.

Tests should inspect outcomes, not construction details.

Key Takeaway: Tests that survive refactoring prove they're testing the right layer — the user's experience, not your code's internal structure.