ByLabelText

The ByLabelText query in React Testing Library is probably the most useful one when you are testing forms and inputs.

The idea is that instead of finding an input based on its id or name attribute, instead you use getByLabelText() to get the input that is labelled (in HTML) with a certain label text.

For example:

const Component = () => {
  return (
    <form>
      <label>
        Your name
        <input type="text" />
      </label>

      <label htmlFor="email">
        Your email
      </label>
      <input id="email" type="email" />
    </form>
  );
};

test('getting inputs by label text', () => {
  render(<Component />);
  expect(
    screen.getByLabelText('Your name')
  ).toBeInTheDocument();

  expect(
    screen.getByLabelText('Your email')
  ).toBeInTheDocument();
});

React Testing Library encourages this behaviour in your tests. Using getByLabelText() helps ensure that your HTML markup is correct and that your inputs are not missing important label text.

Loading full lesson content & code...

Ready to try running tests for this lesson?