Skip to content

Document body should be a focusable element #365

@juanca

Description

@juanca
  • @testing-library/user-event version: @testing-library/user-event@10.4.0
  • Testing Framework and version: jest@25.1.0
  • DOM Environment: jsdom@16.2.0
  • node: node/10.20.1

Relevant code or config (I'm also using React)

it('manages the page tab sequence', () => {
  function TestComponent() {
    return (<ul role="listbox">
      <li role="option" tabindex="0">First option</li>
      <li role="option" tabindex="-1">Second option</li>
    </ul>);
  }

  render(<TestComponent />);

  expect(document.body).toHaveFocus();

  userEvent.tab();
  expect(screen.getByText('First option')).toHaveFocus();

  userEvent.tab();
  expect(document.body).toHaveFocus();

  userEvent.tab({ shift: true });
  expect(screen.getByText('First option')).toHaveFocus();
});

What you did:

Ran the test.

What happened:

The test failed.

    expect(element).toHaveFocus()

    Expected
      <body><div><ul role="listbox"><li role="option" tabindex="0">First option</li><li role="option" tabindex="-1">Second option</li></ul></div></body>
    Received:
      <li role="option" tabindex="0">First option</li>

      76 | 
      77 |       userEvent.tab();
    > 78 |       expect(document.body).toHaveFocus();
         |                             ^
      79 | 
      80 |       userEvent.tab({ shift: true });
      81 |       expect(screen.getByText('First option')).toHaveFocus();

Reproduction repository:

Problem description:

It looks like the tab method does not consider the body as a tabable element. That is actually not true -- at least from doing a quick experiment in Chrome.

The following screenshot is the experiement.

  1. Render a button
  2. Look at active element (body)
  3. Press tab
  4. Look at active element (button)
  5. Press tab
  6. Look at active element (body)

Screen Shot 2020-06-17 at 12 21 03 PM

Suggested solution:

Assuming the focus trap is on the document, always set the body as the first tabable element.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accuracyImproves the accuracy of how behavior is simulatedreleased

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions