In part one of “Unit Testing with Jest in Javascript” we discussed the basics of unit testing and some of the basic ways to implement tests to a vanilla Javascript project, but what if you are using a React framework? When you want to test some of your React components using Jest unit testing, there are a few extra steps that should be taken to ensure proper testing is completed. I would suggest reading part one to the series here before continuing on so that you get the basic knowledge and learn how to set things up before moving forward with this article.

Set Up

In part one we discussed how to set your environment up for testing. The same rules apply, but you will also need to install Enzyme. Enzyme gives you the ability to simulate rendering your application, without actually having to render it. To install both Jest, Enzyme, and the Enzyme adapter for React version 16 at the same time, you can run the following code in your terminal: _npm i --save-dev enzyme enzyme-adapter-react-16._ When you run this line in the terminal you should have a file called setupTests.js that was created. You will then need to place some code in this file that will configure Enzyme to your React adapter based on which version you are using. This code, shown in the photo below, can be found in the Enzyme docs previously linked. This is a file that Enzyme will search for when running tests.

Image for post

Be sure you are importing “Adapter” for the right react version. Check docs!

Mocking Components

When unit testing in React, we want to be able to create mock data that can be used to test out components. We do not want to have to pull this data from the back end, because at that point, it would not be considered a unit test. So we get around this, by creating mock data using enzyme. Enzyme has three different rendering methods: shallow, full DOM, static render markup. Static render markup is actually imported from a third party, and full DOM requires a full DOM API to run it’s tests because it must have a browser-like environment. You can look into these two on your own, but today we will be discussing some of the capabilities provided through shallow rendering. Shallow rendering allows you to test your components as a whole and helps to ensure you are following proper separation of concerns.

#enzyme #jest #test-driven-development #javascript #react #react native

Unit Testing With Jest in Javascript,  — React
1.15 GEEK