react-testing-library is a very light-weight tool for testing React components. Here's a few tips on how to get started with it.
Consider adding data-testid
attributes to your components. This makes them easy to target, and lets us refer to them without having to resort to XPath or CSS.
Using test ID attributes is advocated by many testing frameworks. I first came across it in Cypress, which recommends a very similar practice.
The react-testing-library API comes with getBy
functions that will raise an error if they're not found. By having a test that only has .getBy calls, we effectively make a "smoke" test that will fail if the elements are missing.
The API comes with a fireEvent
helper that lets you simulate any DOM event. Use it to simulate clicks (fireEvent.click(element)
), key presses (fireEvent.keyPress(el)
, and anything else really!
Try @testing-library/jest-dom
to add a few custom matchers.