UI-Testing TypeScript React apps with Puppeteer and Jest

In this article I’d like to show you how to correctly configure Puppeteer in your React project.

Puppeteer is a library developed by Google that helps us to make UI testing way easier.

First of all, let’s start by creating a simple new app by running the create-react-app package.

$ npx create-react-app my-app --template typescript

This is our simple app:

App.tsx

Of course, we need to install some dev-dependencies:

$ npm i -D jest puppeteer start-server-and-test ts-jest ts-node @types/jest @types/puppeteer

Now, we can setup Jest.
Create a new file in the root path of the project called “jest.config.ts”:

jest.config.ts

Make a new folder in the “src” folder called “__tests__”: this is where all our tests will be located.
In this folder, let’s create our first test file called “App.test.ts”:

App.test.ts

This script will:

  1. Launch a new Chromium instance in headless (“invisible”) mode (built-in the Puppeteer package)
  2. Create a new tab that points to our local development server
  3. Click the “increase counter” button 10 times
  4. Check if the value of our counter is 10
  5. Close the browser instance

Before launching our tests, we need to wait for our local server to be up and running.

This is where the start-server-and-test library comes to the rescue.

Open “package.json”:

  1. replace the old "test": "react-scripts test” with "test": "jest”
  2. add "ci": "BROWSER=none PORT=3000 start-server-and-test start http://localhost:3000 test"

Note that the BROWSERproperty is set to none so that we don’t open our browser when launching the development React server.

We’re finally ready to test our app:

$ npm run ci

If we want to have more visual feedback, we can turn off the headless mode.

You can find the code on GitHub here.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store