Closed janhesters closed 2 years ago
You're looking for getByRole('textbox', { description: 'the error message' })
.
There's not distinction between an error message and an accessible description which is why queryErrorByLabelText
could be misused or create wrong test results.
If you want the element that contains the description of an element you're better off with a custom query since there's no clear use case for that. How the description is created is an implementation detail (e.g. aria-description
or aria-describedby="elem1 elem2"
).
Ah, totally forgot about this! Thanks @eps1lon!
@eps1lon Veeeery late thank you for the answer!
How would you query for a <input type="date" />
's or <input type="time" />
's error?
Describe the feature you'd like:
A selector for accessible error messages.
Context: Calls with Kent Podcast Episode "Tests for Accessible Error Messages"
Let's say you have a component like this:
Note: This component uses the common pattern of always rendering the error message, but keeping it empty, when there is no error, which avoids layout shifts. This will become relevant in the suggested implementation below.
It would be awesome if there was a query for grabbing accessible error messages for inputs. In the code above, this would be the
p
tag with theid
of"error-message"
.For example:
could grab the email
input
's error message.Suggested implementation:
I did an example implementation using custom queries. But don't know how good or bad it is. Feedback is welcome! If the feedback is thorough enough, I might be able to submit a PR for this issue.
Let's assume we want to test the component described above.
I created
getErrorByLabelText
like this:We can then hook up our custom queries in our
test-utils/
like this:Finally, we can now write our test:
Note: The test example uses Vitest with happy-dom because those tests run a lot faster than Jest. However, happy-dom is currently broken with user-event, which is why we need the comment at the top.
In the final and real implementation, we should be able to use
getErrorByLabelText
(or whatever the API ends up being) fromscreen
instead of destructuring it from the return value ofrender
.Describe alternatives you've considered:
There are none, except for closing this feature request without an implementation and always using custom queries 🤷♂️
Teachability, Documentation, Adoption, Migration Strategy:
The tests act above as usage examples ☝️