Introduction To Unit Testing with React
By: Patrick Kennedy
Tags: Junior Developer, React, Enzyme, Unit Testing, Jest

The Jest and Enzyme Logo combined to create an amazing suite for testing React applications.

As a Junior Software Developer, I am constantly seeking ways to make myself a better developer. I asked some Senior Software Engineers what I could do to improve. They responded with Unit Testing.

If you are using React as part of your skillset as a developer with just a few years of experience, like myself, it would be worth a couple of hours to get it down, at least the basics. I am here to spread what I know from my experiences and the next bit of this short article will be a super-fast tutorial of writing that first set of tests for a simple component.

Why do I need to write so many tests?

One: Regulating what kind of data is coming into your application and thus regulating whats going into the database.

Two: Longevity of a codebase. Sometimes semantics is not enough and being able to go to a components testing suite can make understanding the code an easier task.

Three: Maintainability. Having the tests gives you more logs to use to your advantage when inevitably a bug arises and something breaks.

Unit Tests Take Time, But, They Save More Time Later.

What is Unit Testing?

I was given a warning about testing the right way. So I will attempt to break it into smaller pieces. A unit test is a method that can be placed into a small portion of an application, components in the case of React. This will verify the behavior of this particular piece of code independently from the others. We have expected behavior, if that behavior is observed, then we have a good piece of code, and if it ever fails, we will know exactly where that failure is.

There is a widely used pattern for Unit Testing known as the AAA Pattern. The AAA stands for Arrange, Act, and Assert. Arrange sets up the code you need for the test and is where the expectations would be set. The Act should be the invocation of the method that is being tested. Assert is a verification that the expected behavior was observed.

You can break up the different types of unit tests into state-based and interaction-based testing. These are fairly self-explanatory and can both follow the AAA Pattern.

Always remember that each test should only test one particular part of the code. Avoiding tests that run more than one parameter will make more difficult later to determine where an error has occurred.

Let’s Write some Unit Tests

We are going to make a form, because, forms are in everything. We need a form that has a First Name and Last Name.

The full name is being stored in the “database” (in this case it's just an array in my state acting as temporary storage). We need to be sure everything is being rendered the way we think it should. We need to confirm that the state is accurately changing from the right input. Finally, we need to make sure the full name is being placed together with the first letter of each part of the name being capitalized and the remainder of the name lower case. For brevity we are only writing one unit test, however, the repo link provided has the other tests for the above scenario.

You can either clone the repo and see how it works or follow along with the setup.

https://github.com/pkennedytx1/simple-unit-test

In the terminal run the following one at a time. Note I am using React version 16.

npx create-react-app simple-unit-tests cd simple-unit-tests npm install react-bootstrap bootstrap npm install --save-dev jest npm install --save-dev enzyme enzyme-adapter-react-16

Quickly throw the bootstrap src link into the public/index.html head tag.

<link

rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"

integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"

crossorigin="anonymous"

/>

Create a new file in the src folder called ‘Form.test.js’ this where we will be writing all the tests. Along with that also make a file in the src folder Form.js for the actual component and FormContext.js for creating a context to pass props around.

Context provides a way to pass data through the component tree without having to pass props down manually at every level. — React Docs.

This will be useful so we can get the values from the inputs. So we can accurately run our tests and have the values placed into the inputs. Within the FormContext.js file place the following code.

Setting up the Context

Next to get this all to work we need to edit the setupTests.js file in the src folder to the following code.

So what's going? From my digging around the enzyme API is the same across all versions of React. However, the different versions of React interact differently with the API. So that's why we installed the specific version for React 16. Essentially this configuring the API so you can work with the functions provided by the enzyme API.

Okay, paste the following code into Form.js to start the component.

We are importing our FormContext Component so we can wrap the form to extract the values we need from the input to inject the tests into the context of the component. This is done by accessing the Provider React component that comes with the Context object. Now we can safely place inputs and test them as we run our testing suite these components that utilize the Context are known as Consumers. More detailed information can be found on the React Documentation.

Now we can take a look at the first test and see how it was written. There are more tests written on the repo for examples of basic unit tests. The following code is in Form.test.js.

First, we have the arrange portion of the test. Here, we explicitly say what is happening to give context to the code that follows.

Next comes the Act portion. Here we setting up the actual code we will need to run the test. According to the enzyme documentation, the .mount() is a method that will re-mount a component or mount it for the first time and can simulate the component going through the mounting lifecycle. So here, we are mounting the CustomForm component and assigning it to a constant wrapper. Next, we can find the specific child component we want to test. In this case, it is the input with a name attribute equal to firstName. Then the simulate function is invoked which requires actions as the first parameter and then, depending on what you are testing, you can change particular attributes of that component. Here we are giving the input with the name attribute firstName the value Anakin.

Finally comes the Assertion of our expected behavior. Because we have an onChangeHandler function we expect that the state of fristName will be updated to Anakin.

Keep in mind this is a very basic introduction and only meant to start you off on a path to becoming more proficient at testing your React applications. Please if you have more to add or suggestions please leave a comment below.

https://github.com/pkennedytx1/simple-unit-test