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

Real-World Example: Form Validation

Test that error messages appear on invalid submission, not that validation functions were called.

Real-World Example: Form Validation

What you'll learn: How to test form validation by asserting error messages appear to users, not by checking if validation logic ran.

The User-Facing Approach

When testing form validation, beginners often spy on validation functions or check internal state to verify "validation happened." But remember: users don't see your validation functions execute—they see error messages.

A robust test submits invalid data and asserts that the user sees the appropriate error feedback. This approach respects the black-box testing philosophy and catches real bugs, like when validation runs but the error message fails to display.

What This Looks Like

Instead of testing whether validateEmail() was called with specific arguments, you:

  1. Render the form
  2. Fill fields with invalid data (empty required fields, malformed email, etc.)
  3. Submit the form using user-event
  4. Assert error messages appear on screen using getByText or getByRole

You're testing the complete behavior chain: input → validation → UI feedback. If any link breaks (validation doesn't run, runs but returns wrong result, or result isn't displayed), your test catches it.

The Anti-Pattern to Avoid

// ❌ Don't do this
expect(mockValidateEmail).toHaveBeenCalledWith('invalid@');

// ✅ Do this instead
expect(screen.getByText(/invalid email address/i)).toBeInTheDocument();

The first approach passes even if the error message never renders. The second tests what users actually experience.

Key Takeaway: Form validation tests should assert that error messages appear to users on invalid submission, not that validation functions were called—this tests the complete user experience and catches display bugs.