Testing nested components in React with Jest and Enzyme

30 April 2019 — Written by Joe Boulos

Medium Article: Testing nested components in React with Jest and Enzyme

Over the last couple weeks, as a student at Hack Reactor, I’ve been working on a project with a team to build a website clone. The website our team chose happened to be an ESPN NFL team page.

The time to complete the project spans over several weeks with many milestones, phases and deadlines to be met. This week we are currently working on implementing tests to ensure our components render correctly and our API’s calls are working correctly.

Our team chose to use Jest as our test suite. All team members, including myself were unfamiliar with Jest and have not created or implemented tests for our code to the extent we were planning for this project.

Many of us had feared the configuration and setup process, however, the configuration and setup for Jest and Enzyme was not as tedious as we expected. With a combination of reading documentation, asking questions on stack overflow, sifting through youtube videos and working together, we were able to successfully install and setup our test suite.

We’ve been able to successfully test our main App component, however, we’ve been running into issues with rendering nested components. As you can see from the picture below, the tests were not recognizing our props. After a couple minutes of scratching our heads in confusion, we decided to take a break and look into this issue further.

After some additional research, it appears that shallow rendering will not test any components within the main App component and that shallow rendering is ignoring the child components within the main App component.

We then chose to implement enzymes mount() method and jests mock() method inside of our test file. This seemed to fix our issues for testing for nested components.

As you can see, the tests now pass for checking to see if a nested component inside our main App was being rendered.

The test was very basic as we wanted to start things off simple so that we could understand the basics and go from there. Having no background with Jest or Enzyme, we were all very happy to solve this issue within a short period of time and can now expand our tests to other nested components.