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

Implementation vs Behavior: A Counter Example

Compare testing a counter's internal state vs testing that clicking increments the displayed number.

Implementation vs Behavior: A Counter Example

What you'll learn: How to distinguish between testing a counter's internal mechanics versus testing what users actually see and do.

The Two Testing Approaches

Imagine you're building a simple counter component. You could test whether clicking the button updates useState's internal value to 1, then 2, then 3. Or you could test whether the displayed number on screen increments each time the user clicks.

The first approach tests implementation. You're asserting that React's state management works as expected—something React already guarantees. You're coupled to how the counter works internally.

The second approach tests behavior. You're verifying that the user sees the correct result after their interaction—what actually matters to your application.

The Counter Example

// ❌ Testing implementation (fragile)
test('increments state when clicked', () => {
  const { result } = renderHook(() => useState(0));
  // Testing internal state value directly
});

// ✅ Testing behavior (robust)
test('displays incremented count when clicked', async () => {
  const user = userEvent.setup();
  render(<Counter />);
  
  const button = screen.getByRole('button', { name: /increment/i });
  const display = screen.getByText('0');
  
  await user.click(button);
  expect(screen.getByText('1')).toBeInTheDocument();
  
  await user.click(button);
  expect(screen.getByText('2')).toBeInTheDocument();
});

Why Behavior Wins

If you later refactor from useState to useReducer or Zustand, the implementation test breaks—even though your counter still works perfectly. The behavior test continues passing because the user experience hasn't changed.

The behavior test asks: "Does the number on screen increase when I click?" The implementation test asks: "Does this specific React hook update?" Only the first question matters to users.

Key Takeaway: Test what users see and do (the displayed count incrementing), not how your component achieves it internally (the state variable changing).