Jest and Puppeteer for frontend e2e tests for React Apps


The following guide is a quick setup for how to get started with writing automated end to end tests using puppeteer and running them using jest for react app.

drawing

Install

If your app was created using create-react-app just run: npm install --save-dev puppeteer or yarn add --dev puppeteer

If your app was created without using create-react-app, run: npm install --save-dev jest jest-cli puppeteer or yarn add --dev jest jest-cli puppeteer

Running

In package.json have the following for create-react-apps (should be there by default so no changes) "scripts": { "test": "react-scripts test" } or this otherwise: "scripts": { "test": "jest" }

For running the tests npm test

Some Basic Code

Let's start by writing a very basic test. By default jest will assume all files with test in their filename are test files and start running those, so we can create a file called App.test.js and add the following:

const puppeteer = require('puppeteer');

let browser
let page

const appUrlBase = 'http://localhost:3000'  
const routes = {  
   public: {  
      register: `${appUrlBase}/register`,  
      login: `${appUrlBase}/login`,  
      noMatch: `${appUrlBase}/somethingrandom`,  
   },  
   private: {  
      home: `${appUrlBase}/home`,  
      account: `${appUrlBase}/account`,  
   },  
};

// control
beforeEach (async () => {  
    browser = await puppeteer.launch({
        headless: false, // headless mode set to false so browser opens up with visual feedback
        slowMo: 5, // how slow actions should be
    }); 
    page = await browser.newPage();  
 })

afterEach (() => {  
    browser.close()  
  })

// You can also define beforeAll and afterAll functions


describe('Login', () => {
    test('users can login', async () => {
        await page.goto(routes.public.login);
        await page.waitForSelector('.signin-form');
        await page.click('input[name=email]')
        await page.type('input[name=email]', 'yomi@mail.com')
        await page.click('input[name=password]')
        await page.type('input[name=password]', 'password')
        await page.click('button[type=submit]')
        await page.waitForSelector('[data-testid="homepage"]')
}, 1600000);
});

Posted by Horia Gug

Comments Section

Horia's Blog

Welcome to my blog! On here you will find random tech articles containing information about things i've learned while working, and other random stuff, enjoy.

Contact

You can find me on GitHub, or via email at: hg_hel@pm.me

Thank you for visiting and enjoy!

Please Log in or Signup to leave comments