DEV Community

Whitney
Whitney

Posted on

Minor Issues: Handling user events with Jest

In an effort to document what I'm working on - and hopefully retain the information as well - I'll be documenting the tidbits that I learn. This includes only the information that I can share publicly, including my personal projects and open-source work. Feel free to make suggestions where you see fit!

Jest testing with React

  • Jest is a popular JavaScript testing framework known for unit and integration testing. This week I used Jest and React Testing Library to test an open-source codebase's reusable button component. Tests are being implemented retroactively and aim to better protect the codebase.

Most of my the button testing went smoothly. Testing for focus, however, proved to be a challenge.

  • Problem: Testing that a button doesn't trap focus

One test needed to assert that a "Tab" press would move focus from the button to the next element. At first, I tried using "fireEvent" to mimic a keyboard press of the Tab key. However, this did not affect the focus. I learned that fireEvent is not the best way to do this.

  • Solution: @testing-library/user-event

FireEvent can be used with Jest tests, but in most cases it is recommended to use @testing-library/user-event instead.

The @testing-library/user-event library mimics user interactions, accounts for accessibility best practices, and manages edge cases where fireEvent may not behave as expected - like in this case!

In this case, userEvent.tab() is all that was needed to successfully imitate a user hitting "Tab" on the keyboard.

test('Button does not trap focus', () => {
  const { getByRole, getByTestId } = render(
    <>
      <Button buttonText="Click me" />
      <input type="text" data-testid="next-element" />
    </>
  );

  const button = getByRole('button', { name: /Click me/i });
  const nextElement = getByTestId('next-element');

  button.focus();
  userEvent.tab();

  expect(nextElement).toHaveFocus();
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)