Puppeteer Login Test example
Puppeteer is a Node.js library utilized for testing webpages within a headless browser, specifically opening Chromium in such a mode.
Let’s start by creating a directory named puppeteertest.
mkdir puppeteertest
cd puppeteertest
Now, initiate a Node.js project with the following command.
npm init -y
This sets up a Node.js project with the necessary basic configuration.
Next, install the Puppeteer dependency.
npm install puppeteer --save
This installs Puppeteer into the Node project.
Create a test.js file and add the JavaScript code to it.
Below are some examples of use cases.
Puppeteer Login example
This example contains login steps.
- First, Launch a headless browser with
headless: false
,
const browser = await puppeteer.launch({
headless: false,
});
- Next, Open a new page in the browser
const page = await browser.newPage();
- Open the login page with the provided URL
const url = "https://www.domain.com/login";
await page.goto(url);
- Once the login page is loaded, enter the username and password
To select input fields, use selectors with id or type, or class.
// use this line to select with an id of the username field
//await page.type('#name', 'username'); or
await page.type("input[type=text]", "username");
// use this line to select with an id of the pwd field
// await page.type('#pwd', 'password'); or
await page.type("input[type=password]", "password");
- Next, Click on submit button using the
id
ortype
selector
// use this line if the button contains the id
//await page.click('#submitBtn');
// use this line to select with button type
await page.click("button[type=submit]");
- Next, wait for the next page to load using
// wait for login authentication result
await page.waitForNavigation();
- Close the browsers
// Close test
await browser.close();
const puppeteer = require("puppeteer");
//create a function for login test
async function logintest() {
const browser = await puppeteer.launch({
headless: false,
});
const page = await browser.newPage();
const url = "https://www.domain.com/login";
await page.goto(url);
// use this line to select with an id of the username field
//await page.type('#name', 'username'); or
await page.type("input[type=text]", "username");
// use this line to select with an id of the pwd field
// await page.type('#pwd', 'password'); or
await page.type("input[type=password]", "password");
// use this line if the button contains the id
//await page.click('#submitBtn');
// use this line to select with button type
await page.click("button[type=submit]");
// wait for login authentication result
await page.waitForNavigation();
console.log("Navigate to New Page URL:", page.url());
// Close test
await browser.close();
}
logintest();
Next, run the code using the node command.
node test.js
This will open a headless browser, perform the login test, and then close the browser.