Issue
Ever since starting with @testing-library for react, I'm confused by the name
attribute. It is possible to get the reference of a rendered button e. g. like this:
// <button>Button text</button>
screen.getbyRole("button", {name: /button text/gi})
In this case name referes to the textNode
inside of the button. The story around inputs is similar where name
can refer to e.g. the id
the name
or the text content.
I'm currently trying to get the reference of a button that is rendered like this:
<button
aria-label="Close"
class="css-1dliicy"
type="button"
>
Create new
<svg>...</svg>
</button>
And the button can not be found with the query:
const createNewButton = screen.getByRole('button', {
name: /Create new/gi,
});
I clearly don't seem to know what the name
property means but I can't seem to find docs on it.
Solution
The name
property refers to the accessible name of the element you're trying to query.
From the ByRole
query docs (third paragraph):
You can query the returned element(s) by their accessible name. The accessible name is for simple cases equal to e.g. the label of a form element, or the text content of a button, or the value of the
aria-label
attribute. It can be used to query a specific element if multiple elements with the same role are present on the rendered content.
As @Moistbobo referred to, since your button has aria-label="Close"
, then Close
will be its accessible name.
Answered By - juliomalves
Answer Checked By - - Timothy Miller (ReactFix Admin)