Book Image

Mastering React Test-Driven Development - Second Edition

By : Daniel Irvine
Book Image

Mastering React Test-Driven Development - Second Edition

By: Daniel Irvine

Overview of this book

Test-driven development (TDD) is a programming workflow that helps you build your apps by specifying behavior as automated tests. The TDD workflow future-proofs apps so that they can be modified without fear of breaking existing functionality. Another benefit of TDD is that it helps software development teams communicate their intentions more clearly, by way of test specifications. This book teaches you how to apply TDD when building React apps. You’ll create a sample app using the same React libraries and tools that professional React developers use, such as Jest, React Router, Redux, Relay (GraphQL), Cucumber, and Puppeteer. The TDD workflow is supported by various testing techniques and patterns, which are useful even if you’re not following the TDD process. This book covers these techniques by walking you through the creation of a component test framework. You’ll learn automated testing theory which will help you work with any of the test libraries that are in standard usage today, such as React Testing Library. This second edition has been revised with a stronger focus on concise code examples and has been fully updated for React 18. By the end of this TDD book, you’ll be able to use React, Redux, and GraphQL to develop robust web apps.
Table of Contents (26 chapters)
1
Part 1 – Exploring the TDD Workflow
10
Part 2 – Building Application Features
16
Part 3 – Interactivity
20
Part 4 – Behavior-Driven Development with Cucumber

Creating a new React project from scratch

In this section, we’ll assemble all of the necessary pieces that you’ll need to write a React application with TDD.

You may have come across the create-react-app package, which many people use to create an initial React project, but we won’t be using that. The very first TDD principle you’re going to learn is You Ain’t Gonna Need It (YAGNI). The create-react-app package adds a whole bunch of boilerplate that isn’t relevant to what we’re doing here—things such as a favicon.ico file, a sample logo, and CSS files. While these are undoubtedly useful, the basic idea behind YAGNI is that if it doesn’t meet a needed specification, then it doesn’t go in.

The thinking behind YAGNI is that anything unnecessary is simply technical debt – it’s stuff that’s just sitting there, unused, getting in your way.

Once you see how easy it is to start a React project from scratch, you won’t ever use create-react-app again!

In the following subsections, we’ll install NPM, Jest, React, and Babel.

Installing npm

Following the TDD process means running tests frequently—very frequently. Tests are run on the command line using the npm test command. So, let’s start by getting npm installed.

You can find out if you already have it installed on your machine by opening a terminal window (or Command Prompt if you’re on Windows) and typing the following command:

npm -v

If the command isn’t found, head on over to the Node.js website at https://nodejs.org for installation instructions.

If you’ve already got npm installed, we recommend you ensure you’re on the latest version. You can do this on the command line by typing the following command:

npm install npm@latest -g

Now you’re all set. You can use the npm command to create your project.

Creating a new Jest project

Now that With npm installed, we can create our project by performing the following steps:

  1. If you’re following along with the book’s Git repository, open a terminal and navigate to the repository directory that you’ve cloned. Otherwise, simply navigate to where you normally store your work projects.
  2. Create a new directory using mkdir appointments and then set it as your current directory, using cd appointments.
  3. Enter the npm init command. This initializes a new npm project by generating a template package.json file. You’ll be prompted to enter some information about your project, but you can just accept all of the defaults except for the test command question, for which you should type in jest. This will enable you to run tests by using the npm test shortcut command.

Editing the package.json file by hand

Don’t worry if you miss the prompt for the test command while you work through the instructions; you can set it afterwards by adding "test": "jest" to the scripts section of the generated package.json file.

  1. Now go ahead and install Jest using npm install --save-dev jest. NPM will then download and install everything. Once completed, you should see a message like the following:
    added 325 packages, and audited 326 packages in 24s

Alternatives to Jest

The TDD practices you’ll study in this book will work for a wide variety of test runners, not just Jest. An example is the Mocha test runner. If you’re interested in using Mocha with this book, take a look at the guidance at https://reacttdd.com/migrating-from-jest-to-mocha.

Commit early and often

Although we’ve just started, it’s time to commit what you’ve done. The TDD process offers natural stopping points to commit – each time you see a new test pass, you can commit. This way, your repository will fill up with lots of tiny commits. You might not be used to that—you may be more of a “one commit per day” person. This is a great opportunity to try something new!

Committing early and often simplifies commit messages. If you have just one test in a commit, then you can use the test description as your commit message. No thinking is required. Plus, having a detailed commit history helps you backtrack if you change your mind about a particular implementation.

So, get used to typing git commit when you’ve got a passing test.

As you approach the end of a feature’s development, you can use git rebase to squash your commits so that your Git history is kept tidy.

Assuming you’re using Git to keep track of your work, go ahead and enter the following commands to commit what you’ve done so far:

git init
echo "node_modules" > .gitignore
git add .
git commit -m "Blank project with Jest dependency"

You’ve now “banked” that change and you can safely put it out of your mind and move on to the following two dependencies, which are React and Babel.

Bringing in React and Babel

Let’s install React. That’s two packages that can be installed with this next command:

npm install --save react react-dom

Next, we need Babel, which transpiles a few different things for us: React’s JavaScript Syntax Extension (JSX) templating syntax, module mocks (which we’ll meet in Chapter 7, Testing useEffect and Mocking Components), and various draft ECMAScript constructs that we’ll use.

Important note

The following information is accurate for Babel 7. If you’re using a later version, you may need to adjust the installation instructions accordingly.

Now, Jest already includes Babel—for the aforementioned module mocks—so we just need to install presets and plugins as follows:

npm install --save-dev @babel/preset-env @babel/preset-react
npm install --save-dev @babel/plugin-transform-runtime
npm install --save @babel/runtime

A Babel preset is a set of plugins. Each plugin enables a specific feature of the ECMAScript standards or a preprocessor such as JSX.

Configuring Babel

The env preset should usually be configured with target execution environments. It’s not necessary for the purposes of this book. See the Further reading section at the end of this chapter for more information.

We need to enable the packages we’ve just installed. Create a new file, .babelrc, and add the following code:

{
  "presets": ["@babel/env", "@babel/react"],
  "plugins": ["@babel/transform-runtime"]
}

Both Babel and React are now ready for use.

Tip

You may wish to commit your source code to Git at this point.

In this section, you’ve installed NPM, primed your new Git repository, and you’ve installed the package dependencies you’ll need to build your React app with TDD. You’re all set to write some tests.