How to automate login from using puppeteer

End to End puppeteer test to automate login form using puppeteer. In this puppeteer tutorial, We are going to write an automation test case for a login page and automate the login page using puppeteer.

End To End puppeteer example to automate login page

Test Scenario 1: Log in with invalid Username and password

  • Launch browser.
  • Navigate to the login page.
  • Enter an invalid username.
  • Enter an invalid password.
  • Click to the login button.
  • Verify the error message.

Test Scenario 2: Log in with valid username and password

  • Launch browser.
  • Navigate to the login page.
  • Enter a valid username.
  • Enter a valid password.
  • Click to the login button.
  • Verify use is log in successfully.
const puppeteer = require('puppeteer');
const expect = require('chai').expect;


describe("User Login",()=>{

    let browser
    let page
    before(async function(){
      browser = await puppeteer.launch({
        headless:false,
        slowMo:100
      })
      page = await browser.newPage()
      await page.goto("http://zero.webappsecurity.com/login.html")
    })

   it("Login with invalid credential",async()=>{
     await page.waitForSelector('#user_login');
     //Enter Username........
     await page.type('#user_login', 'Invalid UserName');
     //Enter Password.....
     await page.type('#user_password', 'Invalid Password');
     //Click to login button..
     await page.click('.btn-primary');
     //Get Error Text
     await page.waitForSelector('.alert-error');
     let ErrorMessage = await page.$eval('.alert-error', element=>element.textContent);
     //Verify text...
     console.log(ErrorMessage);
     expect(ErrorMessage).to.include('wrong');

    })

    it("Login with valid username and password", async()=>{

        await page.waitForSelector('#user_login');
        //Enter Username........
        await page.type('#user_login', 'username');
        //Enter Password.....
        await page.type('#user_password', 'password');
        //Click to login button..
        await page.click('.btn-primary');
        //Verify loged in successfully....
        await page.waitForSelector('.dropdown-toggle');    
     })

    after(async function(){
       await browser.close()
    })

 });

Output: