Title: Understanding the Name Option in React Testing Library
When it comes to testing React applications using the @testing-library, the name attribute might have caused some confusion in your testing journey. In this blog post, we aim to provide a clear understanding of the name option in the React Testing Library and how it affects your tests.
What is the Name Property?
The name property in the React Testing Library refers to the accessible name of the element you’re trying to query. This accessible name can be the label of a form element, the text content of a button, or the value of an aria-label attribute. It helps in querying a specific element when multiple elements with the same role are present in the rendered content.
For example, if you have a button rendered as:
<button>
Button text
</button>
You can get the reference of this button using the getByRole query with the name option:
const button = screen.getByRole("button", { name: /button text/gi });
In this case, the name property matches the textNode inside the button, which is “Button text”.
The Role of Name with Inputs
The same concept applies to inputs as well. The name property in input queries can refer to attributes like id, name, or even the text content of the input element.
Let’s say you have the following input:
<input type="text" id="username" name="username" placeholder="Enter username" />
To get a reference to this input using its name, you can use:
const usernameInput = screen.getByRole("textbox", { name: "username" });
The name property here matches the name attribute of the input element.
Aria-label and Accessible Name
In cases where an element has an aria-label attribute, the accessible name is derived from it. The accessible name takes precedence over the content of the element.
Consider this button:
<button
aria-label="Close"
class="css-1dliicy"
type="button"
>
Create new
<svg>...</svg>
</button>
To query this button using its accessible name, you would use:
const createNewButton = screen.getByRole("button", { name: "Close" });
Here, the accessible name is derived from the aria-label attribute and not the button’s content.
Wrap Up
In this blog post, we explored the name option in the React Testing Library and its significance when querying elements. We learned that the name property represents the accessible name of an element and can be derived from various sources like labels, element content, or aria-label attributes. Understanding how to utilize the name property correctly will help you write effective and reliable tests for your React applications.