Introduction to Puppeteer

Puppeteer

  • Node.js library developed by Google
  • it controls headless Chrome through the DevTools Protocol
  • uses headless Chrome or Chromebit devices, without requiring any browser extensions like Selenium Webdriver or PhantomJS
  • E2E testing: run tests in the browser and then see the results in real-time on your terminal
  • uses the WebDriver protocol to connect with the browser and simulate user interaction with HTML elements or pages

Set Up

  1. app.js file
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    const puppeteer = require('puppeteer');

    (async () => {
    const browser = await puppeteer.launch();
    // create a new page
    const page = await browser.newPage();
    // provide a new URL to browser.newPage()
    await page.goto('https://angelesbroullon-codenotepad.statichost.eu/');

    // close the running process
    await browser.close();
    })();
  2. run npm init to generate the package.json file
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    {
    "name": "hello",
    "version": "1.0.0",
    "description": "",
    "main": "app.js",
    "scripts": {
    "test": "echo \"Error not specified\" && exit 1"
    },
    "author": ""
    }

1st test

  1. Install packages

    1
    2
    3
    npm i puppeteer
    npm i mocha
    npm i selenium-webdriver
  2. Code take screenshots via webdriver

    1
    2
    // take a screenshot of the webpage you navigated to
    await page.screenshot({path: 'example.png'});
  3. Code create a PDF via webdriver

    1
    await page.pdf({ path: 'example.pdf' });
  4. Run the application

    1
    node app.js

Test your Setup

  • Create example.test.js, using mocha syntax

    1
    2
    3
    4
    5
    6
    7
    const puppeteer = require('puppeteer')

    describe("My first Setup Testing",()=>{
    it("Home landing page",async()=>{
    const browser = await puppeteer.launch({headless:false})
    });
    });
  • Run test

    1
    npm run test

Using one Browser Instance with Puppeteer

Run scripts in the headless Chrome browser and access the window object.

  • Testing apps that need access to web resources like localStorage or cookies.

To use one browser instance with Puppeteer, you just need to pass { headless: false } to the launch method.

  • It’s asynchronous so it won’t block the main thread and make your application unresponsive.
1
2
3
4
5
let browser; (async() => {
if(!browser) browser = await puppeteer.launch({
headless: false
}
);