Test Automation using Jest, Puppeteer, and Javascript

0

If you are searching the web to set up you Jest and Puppeteer test then you are in right place. In this blog, you will be reading about how to setup you Jest and Puppeteer test and run them.

jest-puppeteer-javascript

If you are searching the web to set up your Jest and Puppeteer test then you are in right place. In this blog, you will be reading about how to set up your Jest and Puppeteer test and run them.

WHAT IS JEST?

Jest is used by Facebook to test all JavaScript code including React applications. One of Jest’s philosophies is to provide an integrated “zero-configuration” experience.

WHAT IS PUPPETEER?

Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium.

  • Generate screenshots and PDFs of pages.
  • Automate form submission, UI testing, keyboard input, etc.
  • Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.
  • Capture a timeline trace of your site to help diagnose performance issues.
  • Test Chrome Extensions.
  • It is also widely used in Web Scraping

GET STARTED

Let’s go through step by step process of creating an automation framework using Jest, Puppeteer, and JavaScript. At the end of this tutorial, you will know setting up the framework from scratch. Follow the below steps one by one, and if you already know any step then you can skip it and move to the next:

PRE-REQUISITES

Step 1) Install Node.JS

Step 2) Install Visual Studio Code or any other code editor you like

Step 3) Open Visual Studio Code

CREATE YOUR FIRST TEST

Step 1) Create a folder named jest-puppeteer-javascript

Step 2) Create a file named .gitignore and add the below content

node_modules/
temp/
test-results/
downloads/*
log/*

Step 3) Create a file named package.json and add the below content

{
  "name": "jest-puppeteer-javascript",
  "version": "1.0.0",
  "description": "This is Test Automation framework designed using Jest, Puppeteer, and Javascript.",
  "homepage": "https://github.com/codewithmmak/jest-puppeteer-javascript",
  "main": "index.js",
  "dependencies": {
    "jest": "^24.9.0",
    "puppeteer": "^1.20.0"
  },
  "devDependencies": {
    "@types/node": "^10.17.60",
    "node-notifier": "^10.0.1"
  },
  "jest": {
    "testMatch": [
      "**/specs/*.test.js"
    ]
  },
  "scripts": {
    "test": "jest"
  },
  "keywords": [
    "jest",
    "puppeteer",
    "javascript",
    "angular",
    "angularjs",
    "vscode",
    "testing",
    "selenium",
    "automation testing"
  ],
  "author": "Code with MMAK",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/codewithmmak/jest-puppeteer-javascript.git"
  }
}

Step 4) Now go to your project root directory which is jest-puppeteer-javascript and install dependency by running the command.

npm install --save jest puppeteer

Step 5) Now install dev dependency by running the command

npm install --save-dev @types/node node-notifier

Step 6) Now create a folder named specs

Step 7) Create a file named getGitHubRepoDetails.test.js and add the below content

const puppeteer = require('puppeteer');
const testData = require('../config/globalConfig');

describe('GitHub', () => {
    beforeEach(async () => {
        jest.setTimeout(30000);
        // testData.globalJestTimeout;
    });

    it('page title should be "codewithmmak · GitHub"', async () => {
        const browser = await puppeteer.launch();

        const page = await browser.newPage();
        await page.goto(testData.gitHubURL, { waitUntil: 'networkidle0' });
        console.log('User is navigated to site');

        await page.screenshot({
            path: './screenshots/Overview.png'
        });

        const title = await page.title();
        await expect(title).toBe('qaloop · GitHub');
        console.log('Page title is: ' + title);
    });

    it('should display "Repositories"', async () => {
        const browser = await puppeteer.launch();

        const page = await browser.newPage();
        await page.goto(testData.gitHubURL, { waitUntil: 'networkidle0' });
        console.log('User is navigated to site');

        await page.click('nav > a:nth-child(2)');

        await page.waitForNavigation();

        await page.screenshot({
            path: './screenshots/Repositories.png'
        });

        const title = await page.title();
        await expect(title).toContain('Repositories');
        console.log('Page title is: ' + title);
    });

    it('should click "protractor-jasmine-typescript" repository', async () => {
        const browser = await puppeteer.launch();

        const page = await browser.newPage();
        await page.goto(testData.gitHubURL, { waitUntil: 'networkidle0' });
        console.log('User is navigated to site');

        const linkText = await page.$x('//a[contains(text(), "protractor-jasmine-typescript")]');
        await linkText[0].click()

        await page.waitForNavigation();

        await page.screenshot({
            path: './screenshots/protractor-jasmine-typescript.png'
        });

        const title = await page.title();
        await expect(title).toContain('codewithmmak/protractor-jasmine-typescript');
        console.log('Page title is: ' + title);
    });

    it('should get all repository details', async () => {
        const browser = await puppeteer.launch();

        const page = await browser.newPage();
        await page.goto(testData.gitHubURL, { waitUntil: 'networkidle0' });
        console.log('User is navigated to site');

        await page.click('nav > a:nth-child(2)');

        await page.waitForNavigation();

        const repoName = await page.evaluate(() => Array.from(document.querySelectorAll('h3 > a'), element => element.innerText));
        const repoDescription = await page.evaluate(() => Array.from(document.querySelectorAll('div.col-9.d-inline-block > div:nth-child(2) > p'), element => element.innerText));
        const repoTopics = await page.evaluate(() => Array.from(document.querySelectorAll('div.topics-row-container.d-inline-flex.flex-wrap.flex-items-center.f6.my-1 > a'), element => element.innerText));
        const repoProgrammingLanguage = await page.evaluate(() => Array.from(document.querySelectorAll('span.mr-3[itemprop=programmingLanguage]'), element => element.innerText));
        const repoLicense = await page.evaluate(() => Array.from(document.querySelectorAll('span.mr-3'), element => element.innerText));

        console.dir(repoName);
        console.dir(repoDescription);
        console.dir(repoTopics);
        console.dir(repoProgrammingLanguage);
        console.dir(repoLicense);

        await page.screenshot({
            path: './screenshots/all-repo-details.png'
        });
    });
});

RUN TEST

Step 1) Now to run the test open terminal and type the below command

node specs/chrome.js

TEST RESULT

Step 1) You will result in your terminal

CODE REPOSITORY

The sample framework is hosted on GitHub: jest-puppeteer-javascript

Have a suggestion or found a bug? Fork this project to help make this even better.

Star the repo and follow me to get the latest updates

WHAT DO YOU THINK?

Did this work for you?

Could I have done something better?

Have I missed something?

Please share your thoughts using comments on this post. Also, let me know if there are particular things that you would enjoy reading further. 

Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *