Skip to content

fix: escape square brackets in ID selectors#1375

Open
mixelburg wants to merge 1 commit intotesting-library:mainfrom
mixelburg:fix/escape-square-brackets-in-id-selectors
Open

fix: escape square brackets in ID selectors#1375
mixelburg wants to merge 1 commit intotesting-library:mainfrom
mixelburg:fix/escape-square-brackets-in-id-selectors

Conversation

@mixelburg
Copy link
Copy Markdown

Problem

When an element has an ID containing square brackets (e.g. foo[1].bar), calling getByLabelText (or queries that resolve aria-labelledby) throws:

SyntaxError: foo[1].bar is not a valid selector

This happens because querySelector("[id=\"foo[1].bar\"]") interprets [1] as a CSS attribute selector, which is invalid.

Fix

Use CSS.escape() to properly escape IDs before interpolating them into attribute selectors. Applied in two locations:

  • src/queries/label-text.tsgetTagNameOfElementAssociatedWithLabelViaFor
  • src/label-helpers.tsgetLabels (aria-labelledby lookup)

CSS.escape() is available in all environments supported by dom-testing-library (Node >= 18).

Fixes #1404

IDs containing square brackets (e.g. ) cause
 to throw a SyntaxError
because  is interpreted as an invalid CSS attribute selector.

Use CSS.escape() to properly escape IDs before interpolating them
into attribute selectors. Applied in two locations:
- src/queries/label-text.ts (getTagNameOfElementAssociatedWithLabelViaFor)
- src/label-helpers.ts (getLabels aria-labelledby lookup)

Fixes #1404
@codesandbox-ci
Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 2a843f4:

Sandbox Source
react-testing-library-examples Configuration

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant