Question

What is the difference between using `react-testing-library` and `cypress`?

So, react-testing-library is used for unit/integration testing, and cypress is used for e2e testing. However, both appear to do the same thing:

react-testing-library

  • Facilitates mocking
  • Tests as a user would
  • Starts with the top-level component (not a hard and fast requirement, but if you don't you end up with a bunch of duplicate test cases in your sub-component testing)
  • Instant feedback, fast

cypress

  • Facilitates mocking
  • Tests as a user would
  • Starts with the top-level component (the page)
  • Delayed feedback, slow, but provides extra tooling (video proof, stepping through tests, etc.)

Aside from the feedback cycle, they appear to be almost identical. Can somebody clarify what the differences are? Why would you want to use both?

 46  16267  46
1 Jan 1970

Solution

 14

You've answered your question in the first line. If you want to test your React app end-to-end, connected to APIs and deployed somewhere, you'd use Cypress.

react-testing-library's aimed at a lower level of your app, making sure your components work as expected. With Cypress, your app might be deployed on an environment behind CDNs, using caching, and its data could come from an API. In Cypress you'd also write an end-to-end journey, a happy path through your app that might give you extra confidence once you've deployed.

2019-12-04

Solution

 8

Here's an article from Kent C. Dodds answering your question.

My personal take is that the best bang for the buck tests is Cypress E2E tests. This is especially true if you are new to testing and/or at the beginning of a project.

As the project grows, there will come a point where it makes sense to add some extra safety nets with integration tests to make sure certain complex parts of your frontend work. RTL is a better tool for these, runs faster and you can get more granular with it.

And finally, rarely, when you have some specific non-trivial logic, e.g. some complicated transforming of some complicated API data, then unit it.

Also RTL plays really nicely with Mock Service Worker and Storybook. You might not feel it's worth it for either of these tools alone, but put them together and wow you have an amazing, robust testing/documenting/sandboxing system in place!

2022-08-01