Skip to content

getByRole doesn't work for passwords  #1128

Closed
@dwjohnston

Description

@dwjohnston

Note, I think I answered my own answer. But can someone clarify - when searching for password fields - should I just search by labelText?

This is possibly a regression of #737 ?

  • Found "@testing-library/react@13.2.0"
  • Found "jest@27.5.1"
  • Found "jsdom@16.7.0"

Relevant code or config:

const MyPassword = () => {
  return <label>Hello<input type="password" /></label>
}

const MyPassword2 = () => {
  return <><label htmlFor="password">Hello</label><input type="password" id="password" /></>
}
const MyPassword3 = () => {
  return <><label id="label">Hello</label><input type="password" aria-labelledby='label' /></>
}


describe('</>', () => {
  it("Passwords are selectedable label 1", () => {
    render(<MyPassword />)

    expect(screen.getByRole("textbox", {
      name: /hello/i
    })).toBeInTheDocument();
  });

  it("Passwords are selectedable label 2", () => {
    render(<MyPassword2 />)

    expect(screen.getByRole("textbox", {
      name: /hello/i
    })).toBeInTheDocument();
  });

  it("Passwords are selectedable label 3", () => {
    render(<MyPassword3 />)

    expect(screen.getByRole("textbox", {
      name: /hello/i
    })).toBeInTheDocument();
  });
});

What you did:

Try to write tests to assert that password fields exist.

What happened:

These tests fail.

TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/hello/i`

    There are no accessible roles. But there might be some inaccessible roles. If you wish to access them, then set the `hidden` option to `true`. Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole

    Ignored nodes: comments, <script />, <style />
    <body>
      <div>
        <label
          id="label"
        >
          Hello
        </label>
        <input
          aria-labelledby="label"
          type="password"
        />
      </div>
    </body>

      35 |     render(<MyPassword3 />)
      36 |
    > 37 |     expect(screen.getByRole("textbox", {
         |                   ^
      38 |       name: /hello/i
      39 |     })).toBeInTheDocument();
      40 |   });


Reproduction:

Full repro here.

https://github.com/dwjohnston/rtl-password

Run yarn && yarn test

Problem description:

<input type='password'> should have role 'textbox'

Whoops, no it shouldn't - as per the W3 aria spec - it has no role.

Suggested solution:

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