Testing Output, Not Internal Function Calls
What you'll learn: Why verifying render output and side effects matters more than tracking which internal functions executed.
The Core Idea
When testing React components, resist the urge to verify that specific internal functions were called. Instead, test what the user sees or what effects occurred. A function call is an implementation detail; what matters is the outcome of that call.
Think of it like testing a vending machine: you don't verify that the internal "dispenseItem()" function ran—you check that your snack actually appeared in the slot.
Why This Matters
// ❌ Bad: Testing internal function calls
const handleClick = vi.fn();
render(<Button onClick={handleClick} />);
fireEvent.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalled(); // Implementation detail!
This test breaks if you rename handleClick or change how the button internally processes clicks, even if the button still works perfectly for users.
// ✅ Good: Testing the output/effect
render(<Counter />);
fireEvent.click(screen.getByRole('button', { name: /increment/i }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
This test verifies what users care about: the counter incremented. How it happened internally is irrelevant.
When Functions Matter
You should test function calls when they're side effects the user depends on—like API requests or navigation actions—but verify them through their observable outcomes, not by spying on internal helper functions.
Key Takeaway: Test what renders on screen or what side effects occur (API calls, navigation), not whether private helper functions were invoked. Your tests should survive internal refactoring as long as user-facing behavior stays the same.