Testing React with Jest and Enzyme
Think about any app that has to call an endpoint to get some useful data, and now imagine, what would you do to test that? You are probably thinking about calling the endpoint and then checking for the expected value. This approach is good, but we are missing something. When you call an endpoint, you are dispatching an async code, so you must let Jest know when the test has finished before it can continue with another test. If you don’t do that, the test will probably fail because it will start the next one immediately and you won’t know which test will be running when the first callback is returned. Fortunately, Jest has three different ways to handle this: callbacks, promises and async/await.
This is the first option that Jest brings us to handle the async code unit tests. It’s very simple; you have to create a test with a single argument called “done”, and you will use that argument as a function -callback- to indicate that test is finished. If done is never called, the test will fail as we explained in the previous paragraph.
This is the second option and it’s also simple. If you are using promises to get the response of an endpoint, you can also return a promise in your test and Jest will wait for it to resolve. In this case, it’s very important to return a promise. If you expect the promise to be rejected, you must use the catch method to assert the test.
This is the last option to handle the async tests and it’s very similar to the Promises approach. You just add the “async” keyword as the name of the function test, and the “await” keyword in front of the function that calls the endpoint. Using these two keywords lets Jest know that the test will be an async one. If you expect the promise to be rejected, you must use the catch method, as you did for Promises.
Callbacks, Promises and Async code example
Let’s make an example to review the concepts above. Imagine you have an API with an endpoint (GET request) that, given a user ID, returns the user’s info, such as name, age, gender and email. Let’s call the function that sends the request “getUserData” and let’s create a unit test for this example by mixing the three approaches in the same file.
Any developer knows the importance of async code, but not every developer is familiar with how to test it. We tried to summarize the three ways that Jest can handle this kind of tests. Remember that none of these is better than the others, they are just different approaches to do the same thing. You can even mix them and use them in whichever way you find to be easier.