getByRole('form') should work without "name" attribute
See original GitHub issue@testing-library/dom
version: all- Testing Framework and version: Any
- DOM Environment: Any
Relevant code or config:
// this passes, and that's great:
test('form with name', () => {
const form = document.createElement('form')
form.name = 'anything'
const container = document.createElement('div')
container.append(form)
within(container).getByRole('form')
})
// this fails, but I think it should pass:
test('form without name', () => {
const form = document.createElement('form')
const container = document.createElement('div')
container.append(form)
within(container).getByRole('form')
})
What you did:
Originally I thought that a form didn’t actually have the accessible role “form” unless they had a name, but I just did a quick check in the devtools and that appears to not be the case:
I did a bit of research and it appears there aren’t any strong reasons to use a name
attribute for a form, so it seems an odd limitation for us to have.
What happened:
Test fails.
Reproduction:
Put the above snippet in any jest environment you have working with testing library.
Alternatively, you’ll find the same behavior in the browser as well: https://jsbin.com/ceyifo/edit?html,output
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/@testing-library/dom@7.30.4/dist/@testing-library/dom.umd.js"></script>
</head>
<body>
<div>Check the console</div>
<script>
function withName() {
const form = document.createElement('form')
form.name = 'anything'
const container = document.createElement('div')
container.append(form)
TestingLibraryDom.within(container).getByRole('form')
}
function withoutName() {
const form = document.createElement('form')
const container = document.createElement('div')
container.append(form)
TestingLibraryDom.within(container).getByRole('form')
}
try {
withName()
console.log('withName passes')
} catch (error) {
console.error('withName fails', error)
}
try {
withoutName()
console.log('withoutName passes')
} catch (error) {
console.error('withoutName fails', error)
}
</script>
</body>
</html>
Problem description:
It seems odd to me that a form requires a name
attribute to be retrievable by a role query when it appears that the browser considers it to have a role of form
.
Suggested solution:
Update getByRole
to match forms without a name
.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:6 (3 by maintainers)
@ahsatha thanks for reaching out. This issue you’re experiencing isn’t really related to the one described in this issue. The reason you’re seeing this is because the
name
attribute on aform
doesn’t represent the accessible name. You can read in the accessible name computation spec. If I’m not mistaken, you need anaria-label
anaria-labelledyby
or atitle
.@alexkrolick that’s actually already in the docs page in the
*ByRole
page:Do you think that’s enough?