Skip to content

getByRole('form') should work without "name" attribute #937

@kentcdodds

Description

@kentcdodds
  • @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:

image

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/[email protected]/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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions