Testing React Components the Right Way
When it comes to writing UI component code, it’s all about the tests. You know, ideally. In reality, it’s easy to get caught up in the implementation details and forget about the tests. But what makes a good test, anyway?
The Public Interface Matters
Conventional wisdom says to target the public interface when writing unit tests. But what does that mean for React components? It’s not about messages between objects; it’s about the parts that the user can see or interact with. That’s the whole point of a UI component library: managing messages between the user and the application.
User-Centric Testing
So, what text can the user see? What changes when they interact with an element? These are the questions your component unit tests should answer. And, coincidentally, these are similar to the types of requirements that product stakeholders tend to write for user interfaces.
A Simple Weather App Example
Let’s consider a simple weather app with the following specification:
- The page should have a button with the text “Get weather”
- When the user taps the button, the current weather in New York should appear
The Limits of Enzyme and React Test Renderer
Popular tools like Enzyme and React Test Renderer make it easy to write tests that are tightly coupled with implementation details. But what if we decide to use a <div tabindex="0" role="button">
instead of a <button>
? The test breaks. These tools are great, but they don’t encourage user-centric testing.
React Testing Library to the Rescue
React Testing Library (RTL) offers a refreshing alternative. Its API is straightforward and user-centric, allowing you to find elements by label, text, aria-label, or other user-facing attributes. No more brittle tests that depend on implementation details!
Handling Asynchronous Functionality
RTL also provides tools to handle asynchronous functionality, like findByText
, which queries the DOM on an interval until it finds the element or times out. This is as close to plain English as a JavaScript test suite can get.
Write Your Tests First, Worry-Free
With RTL, you can finally write your React unit tests first without worrying about how the source code will look. It’s a game-changer for TDD practitioners.
Get Started with React Testing Library
Want to see how it all comes together? Check out the CodeSandbox example, which includes the tests and source code.
LogRocket: Modern React Error Tracking
Ready to take your React app to the next level? Sign up for LogRocket’s modern React error tracking and get started in minutes.