Simple Example of Testing a React Component
Here’s a simple example of a React component test. There are lots of examples of this out there, but most of them are outdated. I couldn’t find one that showed exactly what I wanted:
- waiting on a promise
- mocking
The following example works as of November 11, 2021 with this setup:
$ npx create-react-app react-testing
...
$ cd react-testing
$ yarn test
We’ll start out with the component:
The service is as simple as can be:
Now, to write a test, use @testing-library/react
, asserting that the data provided by the service shows up:
Then, to add in mocking. Here is one way (there are several different ways that work):