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
$ npx create-react-app my-app --template typescript
This is our simple app:
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”:
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”:
This script will:
- Launch a new Chromium instance in headless (“invisible”) mode (built-in the Puppeteer package)
- Create a new tab that points to our local development server
- Click the “increase counter” button 10 times
- Check if the value of our counter is 10
- 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.
- replace the old
"test": "react-scripts test”with
"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.