Step by step tutorial on puppeteer :: part-4

Convert to Page Object Model (POM)

Now we will convert our Practice Form script to page object model.

Create a folder named pages and inside it, create a file named formSelectors.js

Then write following code:

const formSelectors = {
    url: "https://demoqa.com/automation-practice-form",
    firstName: "#firstName",
    lastName: "#lastName",
    userEmail: "#userEmail",
    gender: "#gender-radio-1",
    phoneNumber: "#userNumber",
    birthDate: "#dateOfBirthInput",
    hobbyCheckBox: "#hobbies-checkbox-2",
    currentAddress: "#currentAddress",
    state: "#state",
    submit: "#submit",
    successMessage: "#example-modal-sizes-title-lg",
    closeButton: "#closeLargeModal"
}

module.exports = { formSelectors };

Here, we have created an object named formSelectors and export the object through module.exports

Now create another file named formPage.js inside the pages folder and write following code:

const { formSelectors } = require('./formSelectors');
class FormSubmissionPage {
    constructor(page) {
        this.page = page;
    }
    async typeFirstName(firstName) {
        await this.page.waitForSelector(formSelectors.firstName);
        await this.page.type(formSelectors.firstName, firstName);
    }
    async typeLastName(lastName) {
        await this.page.waitForSelector(formSelectors.lastName);
        await this.page.type(formSelectors.lastName, lastName);
    }
    async typeEmail(email) {
        await this.page.waitForSelector(formSelectors.userEmail);
        await this.page.type(formSelectors.userEmail, email);
    }
    async clickOnGender() {
        await this.page.click(formSelectors.gender);
    }
    async typePhoneNumber(phoneNumber) {
        await this.page.waitForSelector(formSelectors.phoneNumber);
        await this.page.type(formSelectors.phoneNumber, phoneNumber);
    }
    async typeBirthDate(birthdate) {
        await this.page.waitForSelector(formSelectors.birthDate);
        await this.page.type(formSelectors.birthDate, birthdate);
    }
    async clickOnHobby() {
        await this.page.waitForSelector(formSelectors.hobbyCheckBox);
        await this.page.click(formSelectors.hobbyCheckBox);
    }
    async typeCurrentAddress(address) {
        await this.page.waitForSelector(formSelectors.currentAddress);
        await this.page.type(formSelectors.currentAddress, address);
    }
    async selectState(state) {
        await this.page.waitForSelector(formSelectors.state);
        await this.page.type(formSelectors.state, state);
        await this.page.keyboard.press("ArrowDown");
        await this.page.keyboard.press("Enter");
    }
    async clickOnSubmit() {
        await this.page.waitForSelector(formSelectors.submit);
        await this.page.click(formSelectors.submit);
    }
    async getSuccessfulMessage() {
        await this.page.waitForSelector(formSelectors.successMessage);
        let textElement = await this.page.$(formSelectors.successMessage);
        let text = await this.page.evaluate(e => e.textContent, textElement);
        return text;
    }
    async clickOnCloseButton() {
        await this.page.waitForSelector(formSelectors.closeButton);
        await this.page.click(formSelectors.closeButton);
    }
}
module.exports = { FormSubmissionPage };

Now create a file named browserConfig.js outside the pages folder and write the following code:

const puppeteer = require('puppeteer');
async function startBrowser() {
    let browser;

    browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
        devtools: false,
        args: [
            
            "--window-size=1920,1080"
        ]
    });
    return browser;
}

module.exports = {
    startBrowser
};

Now create another file named SubmitForm.test.js outside the pages folder and write the following code:

const { startBrowser } = require('./browserConfig');
const { expect } = require('chai');
const { FormSubmissionPage } = require('./pages/formPage');
const { formSelectors } = require('./pages/formSelectors');

let browser, page, formSubmissionPage;
before(async () => {
    browser = await startBrowser();
    page = await browser.newPage();
})
before(async () => {
    formSubmissionPage = new FormSubmissionPage(page);
    await page.goto(formSelectors.url);
})
describe("Practice form automation", async () => {
    it("Submit information to the form", async () => {
        await formSubmissionPage.typeFirstName("Salman");
        await formSubmissionPage.typeLastName("Rahman");
        await formSubmissionPage.typeEmail("salmansrabon@gmail.com");
        await formSubmissionPage.clickOnGender();
        await formSubmissionPage.typePhoneNumber("01602020110");
        await formSubmissionPage.typeBirthDate("01 Jan 2000");
        await formSubmissionPage.clickOnHobby();
        await formSubmissionPage.typeCurrentAddress("Gulshan,Dhaka-1212");
        await formSubmissionPage.selectState("NCR");
        await formSubmissionPage.clickOnSubmit();

        let text = await formSubmissionPage.getSuccessfulMessage();
        expect(text).contains("Thanks for submitting the form");
        console.log(text);

        await formSubmissionPage.clickOnCloseButton();

    })
})
after(async () => {
    await browser.close();
})

Now run the script by this command:

npx mocha --timeout=30000 .\SubmitForm.test.js

Taking screenshot while failed testcase:

Add following function before browser closure function into your code:

afterEach('take screenshot on failure', async function () {
    if (this.currentTest.state !== 'passed') {
        const titleName = this.currentTest.title.replace(/\s/g, '_') + '.jpg';
        await page.screenshot({ path: 'output/' + '' + titleName });
    }
});

Now create a folder named output. Then change the assertion value “Thanks for submitting the form” with anything to see if puppeteer takes the screenshot. Now run the script again.

After running the script, you will see that assertion error occurs and screenshot found in output folder.

Generate Report

Install following package:

npm i mochawesome

Now hit this command:

npx mocha --timeout=30000 .\SubmitForm.test.js --reporter mochawesome --reporter-options reportDir=Reports,reportFilename=report.html

After running the script, you will a folder named Reports has been generated and you will find report.html file

about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

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