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>
)
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 general recommended way to find elements in the DOM is taking an approach that resembles the way application is used.
In this particular example name
attribute will not be recognised as pointed out by @ggorlen.
As a fallback for the text input you could either rely on getByLabelText
(assuming you have added a label with htmlFor
), or you could add aria-label
to your text input:
<input type="text" aria-label="userName" />
and then use:
screen.getByRole("textbox", {name: /userName/i});
The "problem" with data-testid
is you have to add it specifically for your tests, instead of relying on more natural findByRole
, findByPlaceholderText
, findByLabelText
.
getByTestId
should be your last resort.
As a follow up I recommend using Testing Playground browser extension, which generates RTL queries for elements, in a similar fashion to find element in browser devTools.
Also, when troubled with searching by name (or other attributes), try to investigate on accessibility features of given element/component to figure precisely how to search for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With