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

Avoiding Tests That Know Too Much

Tests shouldn't know component structure, prop names, or function names unless users interact with them.

Avoiding Tests That Know Too Much

You'll learn: How to write tests that verify behavior without coupling to internal component details like prop names, state structure, or function names.

The Core Principle

A test "knows too much" when it peeks inside a component's implementation — checking specific prop values, asserting on internal state variable names, or verifying that certain functions exist. This creates brittle tests that break whenever you refactor, even if the user-facing behavior stays identical.

Think of it like testing a coffee machine: you shouldn't verify that the internal water pump is called pumpWater() or that the temperature sensor stores values in a variable named currentTemp. You should test that hot coffee comes out when you press the button.

What Tests Shouldn't Know

Your tests shouldn't directly assert:

  • Internal state variable names (expect(component.state.isOpen))
  • Prop names unless they're part of the public API
  • Function names or existence (expect(component.handleClick).toBeDefined())
  • Component structure or DOM hierarchy beyond what affects users

What Tests Should Know

Tests should only verify what users interact with or perceive:

  • Text content that appears on screen
  • Accessible roles and labels
  • Response to user actions (clicks, typing)
  • Visual changes that affect usability

If a user would never see or care about something, your test shouldn't either. You can rename internal functions, restructure state, or change prop names freely — as long as the component still renders correctly and responds to interactions, tests should pass.

Key Takeaway: Write tests that observe your component from the outside, like a user would. If your test knows implementation details the user never sees, it's too tightly coupled.