Which testing framework to use (Enzyme or React Testing Library)?
React Testing Library for new stuff
For new projects, I would recommend using React Testing Library (RTL). This is made easier by create-react-app, which now bundles RTL, and requires no setup to start testing.
One thing you might want to install if you're setting up React Testing Library is React Hooks Testing Library. It's made by the same people as React Testing Library, with the same concepts, and makes testing React Hooks significantly less complicated than other solutions.
Avoiding worst-practices in Enzyme
Typically though, we use the testing framework that's already in the app we're working on. For most companies, that's still going to be Enzyme.
If you're stuck using Enzyme, the best you can do is avoid testing implementation details when using it (which will be a challenge, if you're new to testing).
mount()where possible over
- Rather than checking props and state, try to think of what your user can see, and check that
- Try to avoid blindly copying existing Enzyme tests when writing your own tests. They'll often follow outdated practices such as testing implementation details (we didn't know any better at the time, sorry), and won't actually improve your confidence that the app does what you expect
Convincing your team to migrate
Part of the skillset of a more-senior engineer is to be capable of discussing pros and cons of different solutions in an effort to convince someone of the merits of your solution.
If you're particularly keen on using React Testing Library, it could be worth trying to convince your team to adopt it for new tests only at first, and start migrating tests across to the new framework over time.
In the past I've managed to convince teams I work on to completely change their tooling (like moving to TypeScript), because the existing solution wasn't stopping us from making silly mistakes. You might be able to make a similar argument to get your team to incrementally adopt React Testing Library.
My recommendation for these sorts of migrations is typically:
- For all new code, we'll use the new solution
- For all old code, we'll leave the old solution as-is, unless we need to update existing functionality in the old code. In other words, if you're editing an existing file, take the effort to refactor it to the new way of doing things.
Now that we know which tools to use, let's talk about the types of tests we write in Chapter 4: What are the different types of tests we use in React?
Want to become a better React developer?
I send a single email every two weeks with an article like this one, to help you be a better React developer.
Lots of developers like them, and I'd love to hear what you think as well. You can always unsubscribe.
I'll even send you a free PDF copy of the book you're reading, The Beginner's Guide to React Testing, to start with.