Firing event in react testing library

Hi Campers,

I am still learning react testing library. I understand you can use fireEvent to trigger an event on an element and the function signature of fireEvent is:

fireEvent[eventName](node: HTMLElement, eventProperties: Object)

If I want to dispatch a click event, essentially I have to do something like the following.'Submit')

getByText is one of the built-in selectors.

  1. Can I also do something like'btn'));. Is it considered anti-pattern to do that? I have noticed it works but I have not yet seen it used in a codebase.
  2. Is it possible to access the event parameter in the event handler?

Yes, it’s considered an anti-pattern.
You should generally select your elements by something user could identify (text, role, placeholder, label). If nothing of that is available (e.g. cell in table), you can add data-testid with identifier to the element and query using getByTestId.
render also returns container which is “last resort” selector, that you can use if you really, really can’t use any of the recommended selectors:

const { container } = render(<MyComponent />)
// basically the same as in your example'btn'))

You can pass an event as second parameter of fireEvent:

fireEvent(screen.queryByText('foo'), { target: { value: 'bar' } })
1 Like

Isn’t that bad practice too? Adding identifiers to your elements which might serve no real purpose in production. Because in large code bases, I doubt one would really be able to remove the identifiers before deployment.

However, some folks have expressed to me concern about shipping these attributes to production. If that’s you, please really consider whether it’s actually a problem for you (because honestly it’s probably not as big a deal as you think it is). If you really want to, you can compile those attributes away with babel-plugin-react-remove-properties .

1 Like