Course contentsShow
← React
Lesson 2055 of 2,39646. Testing React with RTLFree lesson

getByLabelText for Form Fields

Finding inputs through their associated labels, the second-best accessibility query.

getByLabelText for Form Fields

What you'll learn: How to query form inputs through their associated labels, RTL's second-best accessibility query after getByRole.

When testing forms, getByLabelText finds inputs through their <label> elements—exactly how screen readers and users navigate forms. This query ensures your form is properly labeled, making it both testable and accessible.

Why Label Text Over Role

While getByRole('textbox', { name: 'Email' }) works for inputs, getByLabelText is more natural for form-specific tests. It mimics how sighted users scan a form: they read the label, then interact with the field. If your test can find an input by its label, so can your users.

How It Works

The query looks for a <label> with matching text, then follows the association to the input—either through the for attribute or by wrapping:

// Explicitly associated
<label htmlFor="email">Email Address</label>
<input id="email" type="email" />

// Implicitly associated (wrapped)
<label>
  Password
  <input type="password" />
</label>

Both patterns work with getByLabelText('Email Address') or getByLabelText('Password').

When to Use It

Use getByLabelText for form controls when the label text is clearer than the role name. It's perfect for inputs, textareas, and selects where the label is the primary identifier.

const emailInput = screen.getByLabelText('Email Address');
const passwordInput = screen.getByLabelText(/password/i);

If your test can't find the input, your form has an accessibility problem—missing or improperly linked labels.

Key Takeaway: getByLabelText queries inputs the same way users read forms—by their labels—ensuring both accessibility and accurate tests.