Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/__tests__/to-have-focus.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,36 @@ test('.toHaveFocus', () => {
expect(() => expect(focused).not.toHaveFocus()).toThrowError()
expect(() => expect(notFocused).toHaveFocus()).toThrowError()
})

test('.toHaveFocus with element in shadow root', () => {
const host = document.createElement('div')
const shadowRoot = host.attachShadow({mode: 'open'})
const input = document.createElement('input')
shadowRoot.appendChild(input)
document.body.innerHTML = ''
document.body.appendChild(host)

input.focus()

expect(input).toHaveFocus()
expect(host).not.toHaveFocus()
expect(() => expect(input).not.toHaveFocus()).toThrowError()
})

test('.toHaveFocus with element in nested shadow root', () => {
const outerHost = document.createElement('div')
const outerShadow = outerHost.attachShadow({mode: 'open'})
const innerHost = document.createElement('div')
outerShadow.appendChild(innerHost)
const innerShadow = innerHost.attachShadow({mode: 'open'})
const input = document.createElement('input')
innerShadow.appendChild(input)
document.body.innerHTML = ''
document.body.appendChild(outerHost)

input.focus()

expect(input).toHaveFocus()
expect(outerHost).not.toHaveFocus()
expect(innerHost).not.toHaveFocus()
})
16 changes: 12 additions & 4 deletions src/to-have-focus.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
import {checkHtmlElement} from './utils'

function getDeepActiveElement(doc) {
let active = doc.activeElement
while (active && active.shadowRoot && active.shadowRoot.activeElement) {
active = active.shadowRoot.activeElement
}
return active
}

export function toHaveFocus(element) {
checkHtmlElement(element, toHaveFocus, this)

const activeElement = getDeepActiveElement(element.ownerDocument)

return {
pass: element.ownerDocument.activeElement === element,
pass: activeElement === element,
message: () => {
return [
this.utils.matcherHint(
Expand All @@ -22,9 +32,7 @@ export function toHaveFocus(element) {
'Expected element with focus:',
` ${this.utils.printExpected(element)}`,
'Received element with focus:',
` ${this.utils.printReceived(
element.ownerDocument.activeElement,
)}`,
` ${this.utils.printReceived(activeElement)}`,
]),
].join('\n')
},
Expand Down