Dom-testing-library: getByLabelText does not match when id has a "." in the string.

Created on 9 Apr 2018  路  4Comments  路  Source: testing-library/dom-testing-library

I had an element that looks like this:

<label for="activity.username">Username</label>
<input id="activity.username" />

and calling: getByLabelText('Username') throws because it won't find the with an id of activity.username. Having a period in the id is valid HTML.

The reason is that on this line:

https://github.com/kentcdodds/dom-testing-library/blob/4bf26d70eda829ca0470c79952f53f5d51ab423b/src/queries.js#L27

the CSS selector # needs to be escaped for a characters that are not valid CSS labels. In this case it is trying to run container.querySelector('#activity.username') but that needs to be escaped to container.querySelector('#activity\\.username'). (double slash to escape in javascript, so the actual string would only have one slash) (see MDN docs).

An alternative would be to use the [id='activity.shift'] selector, as that finds the element without escaping:

So the whole line would be:

return container.querySelector(`[id='${label.getAttribute('for')}']`)
bug help wanted

All 4 comments

Thanks for this @ngbrown! If you could please open a PR for this that would be fantastic. Please add a comment above that line pointing to this issue and briefly explaining why it's not simply using the '#' syntax :+1: Thank you so much for catching this! If you'd like, feel free to add a test that reproduces this bug without these changes as well to make sure we never break this in the future. Thanks again!

Is it OK if I take this?

Sure!

22 should have closed this it looks like

Was this page helpful?
0 / 5 - 0 ratings