Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the name option in react-testing-library?

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.

like image 484
Xen_mar Avatar asked Nov 28 '25 12:11

Xen_mar


1 Answers

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.

like image 177
juliomalves Avatar answered Dec 01 '25 08:12

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!