Sitemap
Lance Laughlin

Lance Laughlin

Testing your React applications

10 min readMay 12, 2018

--

The world of testing in React is vast to say the least. Not only are there a number of tools to use, but there are different types of testing methodologies as well. Jest is a great test runner to start with because it comes packaged with Create React App and is developed by Facebook, the team behind React. We will also use Enzyme as our assertion library, which was created by the team at AirBnb.

This article assumes you will be using Create React App, which will allow us to start testing with Jest without much configuration and Enzyme can be imported as a normal dependency (with a bit of setup, which we will cover)

Unit Testing

One of the things I came across when learning about testing in React, was the many different opinions on the topic. Even the simplest form of testing we can do has a different definition based on who you ask. However, I came to find that the most common definition of unit testing, is a test which runs on a very small part of your application in isolation.

Unit tests can and should be thought of as pure functions. They only take an input and return an output. If your function is producing side effects like hitting an API or interacting with code outside of the component that it lives in, an integration test is probably more appropriate, which we’ll cover later. The closer you can get to using pure functions for your unit tests, the more reliable your tests will be. Remember, the output should always be the same when given the same input, which allows us to test our functions in isolation since all of the logic is contained within the function.

Setting up Jest

If you don’t already have it installed, get create-react-app and follow the instructions provided for creating a new app. Thankfully, the Facebook team has done a great job of making this pretty painless.

Setting up Enzyme

We can simply install Enzyme into our project using npm as a normal dependency. We’ll also need to install an adapter for react.

npm install --save-dev enzyme enzyme-adapter-react-16

Great! There is one last step we need to do in order to start using Enzyme in our project. In your src folder create a new file called setupTests.js and within the file type the following:

import { configure } from "enzyme";import Adapter from "enzyme-adapter-react-16";configure({ adapter: new Adapter() });

Now, in your terminal within your project directory, run the command npm test to start your Jest test runner.

Test Driven Development (TDD)

I prefer to follow a test driven development approach when it comes to writing unit tests. This is again one of those differing opinions in the community but I found it helpful when learning what to test.

If you’re not familiar the idea of TDD is that we write our tests before we write our code. This will probably feel a bit unfamiliar at first but just trust me for now and come along for the ride, plus…it let’s up hop right into learning to test our React applications!

Code Documentation

One of the things I like best about TDD is that it helps me plan out my approach to building features and it can act as a form of documentation, which when working on a team with other developers can really help improve ramp up speed when working on someone else’s code. Imagine picking up a component from someone and having a list of all the functionality of the component, pretty helpful right? I also like to think that having your tests document your code helps your developers become better product experts. If something breaks and a test is thrown, it may give you more insight into how the feature is working.

Let’s get started

Okay, so let’s approach this in a way that should hopefully be familiar with other people who work on a software development team…and that’s with a wireframe.

Press enter or click to view image in full size

Let’s imagine we are given a wireframe for an awesome new DVD trading marketplace. (DVDs are the new crypto). In our TDD approach (and in general) it’s a good idea to start by breaking our design up into components and then we’ll think of the individual features of a component, which will make up our unit tests.

Press enter or click to view image in full size
Components marked up

So, we have 2 main components, our product-item and our cart . Within those are other components that each have a job. That’s another great way to think of what you can unit test. Each item with the blue square has one specific function that we can reliably test against, whether it’s displaying the correct product information, or properly calculating the cart. It warrants a test case.

Describe your tests

After I’ve marked up my components I like to start by describing my tests. Describe is a built in function of Jest, which allows us to group certain tests together into a test suite. It is also a built in function of test which describes a test case.

Remember in TDD we write our tests before we write our code. So the first thing we want to do is create a components folder in our src folder and create a folder for each component. We’ll name then product-item and cart.

Let’s begin with product-item .

Inside your product-item folder, create a file called product-item.test.js . This special naming convention is important so Jest will pick up on your tests when it’s running.

Let’s beginning describing our component test case

product-item.test.js

Above you’ll see that we have one main describe block for the entire product item. Within that we have a describe block for making sure the children components render and then the functionality for the product form. You might be wondering…what are we actually testing here? You’re right, we aren’t testing anything yet. This is simply to document our component behavior, and we’ll continually test against these cases and we develop. In case it’s not clear, one of the best parts of testing is that every time we save, each and every test we have written will run, ensuring that if we do cause a bug somewhere else in our code, we’ll know right away. Cool!

Writing our first tests

Okay, let’s get started. Our first tests will ensure that our components render properly on the screen. This is helpful in case we ever write a bug that prevents a component from rendering.

So the first thing we’ll need to do is to import a couple new modules into our test file. At the top of your product-item.test.js file import the following

import { shallow } from 'enzyme';import ProductItem from './product-item';

shallow is a API from enzyme, which allows us to shallowly render our components for testing. shallow is great for unit tests because it renders only the component we are testing, and does not render out any children components within it. We’ll talk more about mount later, which renders the whole tree and is perfect for integration tests.

We also import ProductItem which doesn’t exist yet; however, the idea of TDD is that we write our tests intentionally to fail first, this helps us prevent false positives for our tests and ensures that they are working correctly.

Within our first describe block, we’ve shallowly rendered our ProductItem component at to top of our first describe block. It makes sense to put it here because all of our sequential tests will use this shallowly rendered component.

In our first nested describe block we have our first It statement. Within that we see our very first expect clause. expect is a part of the enzyme package and will be used for our very first assertion statement. Anyone who has used jQuery should find the selector syntax pretty familiar.

Get Lance Laughlin’s stories in your inbox

Join Medium for free to get updates from this writer.

Our first test is a simple one. We want a check to make sure that each of our children elements in our component render correctly. I think this check is pretty self explanatory so I won’t spend much time on it. If you’re interested in learning more about this assertion, check this out.

Okay, so we’ve written our test, and if we check our test runner we will see that we now have a failing test! This is exactly what we want in our TDD approach. Let’s get to work on making this test pass. The first failure we see is our test is unable to find our component, because we haven’t written it yet.

Press enter or click to view image in full size
Our first failing test

Go ahead and create a file called product-item.js in the same directory as your test and create a standard React component

Upon saving we’ll see our next failing test case:

Press enter or click to view image in full size

This is a your first real failed test. This is the exact failure message you would see if your product title didn’t render for some reason. As you can see in our assertion statement, we are looking for an element with the class of .product-title . It’s worth note that you can use different selectors other than a class. You can also target via ID, or probably more useful in a real world application, by a JSX component.

Let’s fix this up. Head over to your product-item file and let’s add an element with the class product-title

aaaaaand. Walla!

Press enter or click to view image in full size

All of our test are passing!

Alright, let’s do a unit test that goes past simple rendering. Probably the most useful test in a real world environment would be ensuring that a user cannot add a quantity of items to their cart that’s greater than our inventory. Again, let’s write our test first and then we’ll write the code to pass it.

f

Okay, so there are a few new things happening here. First, we are mocking up some data to send into our component. This is often referred to as arranging in testing. Which means we are arranging some data for our test to use. Next we are actually now passing that productData object into our shallowly rendered component.

So this is where you can see testing starting to shine a bit. We can actually find our input field (which again, doesn’t exist yet) and simulate a user typing in the value of 10 into it. This is often referred to as acting in testing.

When we check our test runner now, we see a new failed test:

Press enter or click to view image in full size

This is an error you’ll see when Enzyme is unable to find the element that you’re attempting to simulate the event on.

Let’s go ahead and create the elements the test requires to run.

Nice, that error has gone away but now we have a new one.

Press enter or click to view image in full size

Our test for our disabled button is failing because, well…we haven’t done anything to make this test pass. Let’s do that now.

I won’t go much into this implementation since this article is not about React itself but this should all seem pretty familiar. Your test should be passing now!

Okay, I want to do one more example in this file to cement this idea a bit more. We have one more test related to the test we just wrote and that is to show a message when we’ve entered a quantity that is more than the available quantity.

One new thing here. We are now using .text() to inspect the text inside our error message div. It’s also worth nothing that this test does 2 things really. It will also fail if it’s not able to find the error message. How’s that for efficiency?Let’s take a look at the component now.

Again, I won’t go too much into the implementation of this. But we are now checking that the error message shows up and shows the correct message.

Optimizing Your Tests

I think this is a good opportunity to introduce a couple new concepts to make our test a bit less verbose. Looking at our describe block for Product Form we can see there are some redundancies. The first 3 lines of those test are exactly the same. We arrange our data, shallowly render our element with that data and we simulate a user input. Enzyme has a nice helper here called beforeEach which allows us to execute some code before every test in a test suite. Let’s move those 3 lines to a beforeEach method.

Nice, that’s much cleaner.

Integration Testing

Okay, I think we have a good understanding of unit tests, let’s start diving into writing an integration test. Remember, an integration test is great for testing multiple components interacting with each other. We have a perfect example of that with our sample app. Let’s test that a user can add an item to their cart.

The process for writing an integration test will start off pretty similarly to our unit test. So we’ll start by describing our interactions in App.test.js

So a couple new things here. We are now using mount because we want our children components of App.js (Cart and Product Item) to render so we can test their DOM values.

Let’s write the code in App.js to pass this test.

If we run this code we’ll see our tests are passing. Our first integration test!

Conclusion

In conclusion, we have learned about test driven development, breaking our tests into small, single purpose and reusable cases, unit testing and integration testing.

There is much more to the world of testing but I hope this helps give you an idea of what writing tests look like and how it might integrate into your workflow. Thanks for reading!

--

--