As usual, opinions are personal and may contain some bias.
Over the years I found a common recurring pattern wherein React component tests are done by asserting on the internal behaviour of the function rather than the actual output.
Frontend unit tests must treat the test subject, our React Component as a black box just like how an end user might.
For example, when I am filtering apartments in Airbnb, I only care about the information I see on the screen and how it reacts to the filters I apply. At no point do I need to know if the underlying React component state has updated or if the text is an h2 or bold.
2 popular ways I know of, using which we can unit test React components:
Enzyme
React Testing Library
TL;DR I would use React Testing Library approach for writing meaningful unit tests.
What are we testing?
Here, how we render the joke is an implementation detail. The fact that the joke gets fetched and rendered on click of the button is the behavior.
For example, later on we could render the joke inside a <p/> tag. The behavior of the component would remain unchanged and as such we should not have to touch our tests for this change.
Enzyme test
Here, you will see we are extracting text content of the <h3/> element using wrapper.find('h3').text(). So based on our contrived example above, if we were to convert the <h3/> into a <p/>, our test will break. For a larger, more complex component, the changes will increase exponentially. This makes refactors hard.
React Testing Library Test
Here, we are only testing for the behavior. So, as long as the behavior stays same, an update in how we render the joke for this case makes no difference. For larger projects with lot more complexity, passing tests across refactors will give developers confidence and help them move fast.
Created for showing a demo of testing the same React component using Enzyme and React Testing Library
Where with Enzyme, it is more around the implementation details, with React Testing Library it is around the behavior.
This will trigger the tests and both will pass of course.
What are we testing?
import"./styles.css";import{useState}from"react";import{get}from"axios";exportdefaultfunctionApp(){const[joke,setJoke]=useState(null);const[error,setError]=useState(null);constfetchJoke=async()=>{try{const{ data }=awaitget("https://api.icndb.com/jokes/random");if(data.type===