hand sketched logo of electrons orbiting a nucleus

TIL: User-event for testing DOM interactions

Just show me the code:

// bad
test('change input value', () => {
  render(<MyComponent />);
  const input = screen.getByRole('textbox');
  fireEvent.change(input, { target: { value: 'new value' } });
  expect(input.value).toBe('new value');
});

// good
test('change input value', async () => {
  const user = userEvent.setup();
  render(<MyComponent />);
  const input = screen.getByRole('textbox');
  await user.tripleClick(input); // focus and select all text
  await user.type(input, 'new value');
  expect(input.value).toBe('new value');
});

Why?

When building out components you there is a lot of event handling that goes on beyond "change" which is what fireEvent.change triggers.

For example, you might have a component that listens for "input" events to update a character count, or a component that listens for "focus" and "blur" events to show a tooltip.

Further Reading

Original inspiration Why you should test with user-event