Testing arrow key keyboard navigation of a radio button group

Viewed 1458

I'm using testing-library to test an implementation of a radio button group. I can test that tab sets focus to the first radio option, but I can't get the arrow key navigation to test properly.

Here's the test I have:

import {
  getByLabelText,
  render,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
...

test('arrow key navigation', () => {
  const {container} = render(
    <div>
      <label htmlFor="apple">
        Apple
        <input type="radio" value="apple" id="apple" name="fruit"/>
      </label>
      <label htmlFor="banana">
        Banana
        <input type="radio" value="banana" id="banana" name="fruit"/>
      </label>
    </div>
  )

  const apple = getByLabelText(container, 'Apple')
  const banana = getByLabelText(container, 'Banana')

  userEvent.tab()
  expect(apple).toHaveFocus() // This assertion passes
  userEvent.keyboard('{arrowright}')
  expect(banana).toHaveFocus() // This assertion fails
})

2 Answers

I'm running into the same situation here, I found out the component didn't rerender which it should be, that's the reason why the test fail

I was able to get this to work using userEvent.type and not .keyboard. This works for me:

userEvent.tab();
expect(apple).toHaveFocus();
userEvent.type(apple, '{arrowright}');
expect(banana).toHaveFocus();
Related