Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Testing Library: When to use userEvent.click and when to use fireEvent

Tags:

I'm presently learning React-Testing-Library.

I'd like to test mouse interaction with an element. Presently it's a bit unclear to me the difference between userEvent.click(element) and fireEvent.click(element). Are both recommended for use, and in the example below are they being correctly implemented?

const mockFunction = jest.fn(() => console.info('button clicked'));
const { getByTestId } = render(<MyAwesomeButton onClick={mockFunction} />);
const myAwesomeButton = getByTestId('my-awesome-button');

// Solution A
fireEvent(myAwesomeButton)
expect(mockFunction.toHaveBeenCalledTimes(1);

// Solution B
userEvent.click(myAwesomeButton);
expect(mockFunction).toHaveBeenCalledTimes(1);

Thanks in advance for any clarity.

like image 253
user2190690 Avatar asked Sep 22 '20 08:09

user2190690


People also ask

What does fireEvent click do?

Consider fireEvent. click , which creates a click event and dispatches that event on the given DOM node.

What is testing library userEvent?

user-event is a companion library for Testing Library that simulates user interactions by dispatching the events that would happen if the interaction took place in a browser.

Should fireEvent be in act?

You NEVER need to wrap userEvent or fireEvent in act. They are *already* wrapped in act. Some have noticed that they see an "act warning" go away when wrapping these in an async act. The warning would go away just as well if you added: `await act(async () => {})` on the next line.

What does fireEvent change do?

Using fireEvent. change() on a select element fires the event handler, but doesn't update state.


1 Answers

Behind the scenes, userEvent uses the fireEvent. You can consider fireEvent being the low-level api, while userEvent sets a flow of actions.

Here is the code for userEvent.click

You can see that depending of which element you are trying to click, userEvent will do a set of different actions (e.g. if it's a label or a checkbox).

like image 55
Guilhermevrs Avatar answered Sep 22 '22 15:09

Guilhermevrs