A new querySelector to select elements based on role. I have a dialog that while I can query inside the dialog just fine I cannot first a click to close the dialog because all the current queries target elements inside the dialog so the out of bounds click handlers do not fire.
const queryAllByRole = queryAllByAttribute.bind(null, 'role')
const queryByRole = queryByAttribute.bind(null, 'role')
const queryAllByRole = queryAllByAttribute.bind(null, 'role')
function getAllByRole(container, id, ...rest) {
const els = queryAllByRole(container, id, ...rest)
if (!els.length) {
throw getElementError(
`Unable to find an element by role=${id}`,
container,
)
}
return els
}
function getByRole(...args) {
return firstResultOrNull(getAllByRole, ...args)
}
I'm using Material UI where there is a lot of abstraction in DOM that I can't put data-testid on the outer dialog. So targeting it by testid won't work for triggering the onClose event.
The only thing I've considered is writing the
const dialogConstainer = container.querySelector('[role="dialog"]')
And then writing assertions from there.
This is a non breaking change as it is only an addition to the existing query set.
getByRolegetByRole(
container: HTMLElement,
text: TextMatch,
options?: {
exact?: boolean = true,
collapseWhitespace?: boolean = false,
trim?: boolean = true,
}): HTMLElement`
A shortcut to container.querySelector(`[role="${yourRole}"]`) (and it
also accepts a TextMatch).
// <div role="dialog">...</div>
const dialogContainer = getByTestrole(container, 'dialog')
Funny, I was thinking something similar now after the recent discussion in gnapse/jest-dom#55. It would be a nice addition.
Thanks for the thorough feature request @JeffBaumgardt! I'm in favor of this. Would you like to implement it?
Can do I'll have a PR later today.
Closed via #94
Most helpful comment
Can do I'll have a PR later today.