testing-library / testing-library/user-event

`clear()` throws error (`The element to be cleared could not be focused`) in shadow DOM

Open
#1,143 3 comments 13 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
TypeScript
Stars
2.3k
Forks
258
PR merge metrics
No merged PRs in 30d

Description

Reproduction example

https://stackblitz.com/edit/js-4pfvam?file=index.js

Prerequisites

To repro, create an <input> in a shadow root, and then try to clear() it:

import userEvent from '@testing-library/user-event';

const appDiv = document.getElementById('app');

appDiv.attachShadow({ mode: 'open' }).innerHTML = '<input type=text>';
const input = appDiv.shadowRoot.querySelector('input');

userEvent.clear(input); // throws the Error
Expected behavior

An <input> should be clear()able regardless of whether it's in a shadow root or not. It's still focusable, even if it's in a shadow root.

Actual behavior

The error is thrown: The element to be cleared could not be focused

The root cause seems to be this line of code:

https://github.com/testing-library/user-event/blob/7a305dee9ab833d6f338d567fc2e862b4838b76a/src/utility/clear.ts#L12C1-L14

The issue is that document.activeElement is not sufficient for determining the active element in this case. You would need to drill down one level deeper into the shadow root:

document.activeElement // shadow host element
document.activeElement.shadowRoot.activeElement // <input>
User-event version

14.4.3

Environment

See repro above.

Additional context

This used to work in a previous version of @testing-libray/user-event. It seems to have started throwing in this commit: https://github.com/testing-library/user-event/commit/1cda1b1b9726c2e7db213ec543f96b3fde2d10b8

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with src/utility/clear.ts, especially the focus check identified in the issue, and reproduce the failure using the linked StackBlitz example. Trace how activeElement is resolved through the shadow root, then verify that clear() succeeds for the shadow-root input without regressing ordinary inputs.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
frontend, testing
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.