Skip to content

Browser Interactivity API should escape CSS IDs when building selectors #6211

@zacharyvoase

Description

@zacharyvoase

Describe the bug

The issue is here:

— the raw ID is inserted into the CSS selector string as-is, but that may not always produce valid CSS, and causes an error during the test.

You can reproduce this issue just by defining a <button id=":foo"> and trying to use userEvent.click() on it.

Almost any string can be a valid HTML ID (see here), but that does not mean it can be used unescaped in a CSS selector. It is possible to escape characters outside the regular range by following these instructions. One could write a small function, e.g., sanitizeHtmlIdForCss(htmlId: string): string, and just call that on el.id before passing it into the string interpolation in the line of code I linked to above.

If this seems worth addressing I can submit this PR myself, just let me know. Thanks!

Reproduction

This is hard/impossible to reproduce in Stackblitz because it only applies in the browser, and I don't think Stackblitz can run those. But if you have a local project that runs tests in the browser, try creating an element with an ID of :foo, and call any userEvent method on it.

System Info

System:
    OS: macOS 14.5
    CPU: (10) arm64 Apple M1 Max
    Memory: 653.55 MB / 64.00 GB
    Shell: 3.7.0 - /opt/homebrew/bin/fish
  Binaries:
    Node: 21.7.1 - /opt/homebrew/bin/node
    Yarn: 1.22.19 - /opt/homebrew/bin/yarn
    npm: 10.5.0 - /opt/homebrew/bin/npm
  Browsers:
    Chrome: 126.0.6478.183
    Safari: 17.5
    Safari Technology Preview: 18.0
  npmPackages:
    @vitejs/plugin-react: ^4.2.1 => 4.2.1
    @vitest/browser: ^2.0.4 => 2.0.4
    vite: ^5.3.4 => 5.3.4
    vitest: ^2.0.4 => 2.0.4

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    feat: browserIssues and PRs related to the browser runnerp3-minor-bugAn edge case that only affects very specific usage (priority)pr welcome

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions