Skip to content

[Feature] getByRole should default to exact: true #27483

Closed

Description

getByRole is most often used with the name option to query based on the target's accessible name -- a great practice for ensuring your elements have accessible labels. However, the name option is (unexpectedly I think) a case-insensitive substring match by default:

By default, matching is case-insensitive and searches for a substring, use exact to control this behavior.

I would expect that most developers would use a RegExp when they actually want a lowercase substring match, ie name: /address/i. I think the expected behavior for strings is typically an exact match.

This less-strict than expected behavior can easily lead to accessibility bugs slipping through the tests. For example, say you use a pencil icon component that sets the alt text / label of the icon to "pencil". This is pretty normal, since if you use that icon in prose you'd want it to have some alt text. But then say you use it in a button along with the visible text "Edit", ie:

<button>
  <pencil-icon />
  Edit
</button>

This button will be located by getByRole("button", {name: "Edit"}) so most would assume the button is labelled as expected. But the actual label for the button is "pencil Edit", which doesn't make any sense for a screen reader user.

I think that this API should default to setting the exact option to true:

exact: Whether name is matched exactly: case-sensitive and whole-string... Ignored when name is a regular expression. Note that exact match still trims whitespace.

This would be a breaking change, but I think it would be worth it to make the library safer. If we wanted to avoid the breaking change, maybe a global setting to control this instead?

Related:

Activity

  1. pavelfeldman commented on Oct 6, 2023

    @pavelfeldman
    Member

    We decided to keep our text matchers case-insensitive by default and do not intend to change it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions