Commands for Testing: React Applications

Learn how to automate React application testing.

Introduction

In previous chapters, we’ve seen that we can run tests with pytest and Jest, and compile documentation with Sphinx all from the command line. Therefore, we can automate them. If a test fails, the script will fail, and the commit will be rejected.

It’s useful to know that the Git hook scripts will be executed with the repository’s root as their working directory regardless of where in the repository the git commit command was run. So we’ll need to change directories, using cd, in the pre-commit script to make sure commands execute from the right places.

Automate React application testing

Ideally, we’d be able to add npm test in the script and get the Jest tests to work. However, there is a problem scripting the Jest testing, because when we run npm test, it creates a watcher that continues to check for changes and re-test when needed. Using this, the pre-commit script would never end, until we exited from the watcher. That’s not automation. We need the test to run once and exit with success if the tests pass or fail if they don’t. Fortunately, this is a common use case, and the create-react-app script that handles the testing already allows for it.

Pre-commit script

We only need to specify the environment variable CI=true. (CI stands for continuous integration.) In a script, the example shown below, looks like this, where we’ve left off the shebang line because it’s a shell script.

Get hands-on with 1200+ tech skills courses.