How to fetch element with 'name' attribute in react-testing-library

Viewed 20542

I'm testing my react app with react testing library and jest.

And I want to know how to fetch element with 'name' attribute in react-testing-library.

For example, in the following page, is it possible to fetch this element with "userName"?

<input type="text" name="userName" />

Or should I set data-testId into the element and use getByTestId method?

return (
  <div>
    <input type="text" name="userName" />
  </div>
)
2 Answers

You can use the returned container. The container is a DOM node and supports the querySelector method, which accepts a CSS selector to find an element. Same approach as in this more detailed answer.

For example:

const { container } = render(<MyComponent />);
const inputEl = container.querySelector(`input[name="userName"]`);

The recommended way is to use screen.getByRole("textbox", {name: /userName/i}), as it resembles the way application is used.

The "problem" with data-testid is you have to add it specifically in order for your tests, instead of relying on more natural findByRole, findByPlaceholderText, findByLabelText.

getByTestId should be your last resort.

Related