Repository navigation
fix(to-have-focus): resolve the active element through shadow roots - #739
FrancoKaddour wants to merge 1 commit into
Conversation
Closes testing-library#722. toHaveFocus checked ownerDocument.activeElement === element, but when focus is inside a shadow root document.activeElement resolves to the host, not the truly focused element. Walk down nested shadow roots (via a getActiveElement helper) in both the pass check and the failure message. Degrades to doc.activeElement for regular elements, so existing behavior is unchanged.
|
Just thinking about that now: I've been using We could also add |
|
Good thought — I tried jsdom doesn't propagate Re |
|
Ah right, I'm not using that in jsdom indeed. |
Closes #722.
Problem
toHaveFocuscheckselement.ownerDocument.activeElement === element. When focus moves into a shadow root,document.activeElementresolves to the shadow host, not the element that actually has focus (which lives atshadowRoot.activeElement). As a result,toHaveFocuscan never pass for any element inside a shadow root:Fix
Add a small
getActiveElementhelper that walks down nested shadow roots to find the truly focused element, and use it both in thepasscheck and in the failure message (so the "Received element with focus" diagnostic points at the real element rather than the host). For regular elements with no shadow root it degrades todoc.activeElement, so existing behavior is unchanged.Thanks to @julienw for the clear report and the suggested approach.
Tests
Added coverage for a focused element inside a shadow root and inside nested shadow roots. Both fail on
mainand pass with this change; the existing.toHaveFocustest is unaffected.