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
app.js
file1
2
3
4
5
6
7
8
9
10
11
12const 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();
})();- run
npm init
to generate thepackage.json
file1
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
Install packages
1
2
3npm i puppeteer
npm i mocha
npm i selenium-webdriverCode take screenshots via webdriver
1
2// take a screenshot of the webpage you navigated to
await page.screenshot({path: 'example.png'});Code create a PDF via webdriver
1
await page.pdf({ path: 'example.pdf' });
Run the application
1
node app.js
Test your Setup
Create
example.test.js
, using mocha syntax1
2
3
4
5
6
7const 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 | let browser; (async() => { |