Introduction to Enzyme
Get an introduction to testing with React and how to create React projects from scratch.
We'll cover the following
Testing React with Enzyme
JavaScript web development can be divided into two eras: pre-React and post-React. Pre-React was all chaos. Suppose you wanted to make a button-toggle a popup when clicked. You’d add code nowhere near the button markup to add an event listener for the button click. The event listener you’d write would directly alter the DOM to show or hide the popup. Code was scattered without rhyme or reason. Unit tests were almost unheard of.
Thankfully, we live in the age of React. Now individual pieces of the app can be isolated as components. The DOM tree they render is a pure function of their props (React parlance for data provided to the component) and their internal state. And that purity makes them a breeze to test.
In this chapter, you’ll use a test-driven approach to build a complex component one piece at a time. You’ll use the Babel compiler to incorporate React’s powerful JSX syntax into your tests. You’ll combine the speed of Jest with the ease of Enzyme, a harness that lets you test individual React components in isolation. Along the way, you’ll take advantage of the tools introduced in the previous chapter, applying them to a cutting-edge React stack.
Starting a React project
Our project for this chapter, and for the remainder of the course, will be a carousel component. Carousels have become ubiquitous on the web, yet many implementations fall short in various ways. By building your own, you’ll be able to adapt it to your project’s needs.
-
Create a new directory called
test-driven-carousel
and open it in VS Code:$ mkdir test-driven-carousel/ $ code test-driven-carousel/
-
Use VS Code’s “Git: Initialize Repository” command, or run the following in the command line:
$ git init
-
Once the repo is initialized, add the
.gitignore
from the previous chapter://.gitignore node_modules/ .vscode/
-
Then create a
package.json
using npm:$ npm init -y
-
As in the previous chapters, add a
"private": true
entry to thepackage.json
to silence various npm warnings:
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy