ReactJs Tutorials

Testing async code with Jest

After a little bit of struggle, I have managed to implement a jest that correctly tests an async fetch call. That is, suppose clicking a button initiates a POST request, and upon success some action takes place or some message gets displayed. I needed a test to assert that the action indeed took place.

My component looks as follows:

How to mock fetch and a state change in jest, react

tl;dr: I decided not to do it.

Since Enzyme is obsolete as of React 18, you would use <render /> and not <mount />. Therefore, you don't have a wrapper to manipulate and observe the state of the component being tested.

Furthermore, I'm really only testing the component because it's a best practice, and because of the expectation of future complexity. The state change itself is trivial: