×
☰ See All Chapters

Puppeteer handling dropdown

Puppeteer supports testing Dropdown and List controls using “select” or “type” method of “ElementHandle” class.

const occupation = await page.$("#occupation");

//select option by select method

await occupation.select("PRIVATE");

//select option by type method, by typing in value

await occupation.type("PUBLIC");

To check the select value, read value property of ElementHandle as shown below:

const selectedValues = await (await occupation.getProperty("value")).jsonValue();

console.log(selectedValues);

If selecting multiple values is enabled, we can select by passing multiple values to select method.

const tools = await page.$("#tools");

await tools.select("Selenium", "QTP");

You can write the script and test these using our Test Page

puppeteer-handling-dropdown-0
 

Puppeteer dropdown example

import { launch, Page } from 'puppeteer';

example();

async function example() {

    const browser = await launch({headless : false});

    const page = await browser.newPage();

    await page.setViewport({ width: 1366, height: 768});

    await page.goto('https://www.tools4testing.com/contents/puppeteer/testpages/registration-form-testpage');

        await enterDetails(page);

    //wait for some time before closing, specify time in milliseconds

    await wait(5000);

    //Close browser

    await browser.close();

}

 

async function enterDetails(page: Page) : Promise<void> {

    const occupation = await page.$("#occupation");

    //select option by select method

    await occupation.select("PRIVATE");

    await wait(2000);

    //select option by type method, by typing in value

    await occupation.type("PUBLIC");

    //Check if selected value is correct

    await wait(1000);

    const selectedValue = await (await occupation.getProperty("value")).jsonValue();

    console.log(selectedValue);

    //Multi select DropDown ---------------------------

    const tools = await page.$("#tools");

    await tools.select("Selenium", "QTP");

    //select option by select method

    await wait(1000);

    const selectedValues = await (await tools.getProperty("value")).jsonValue();

    console.log(selectedValues);

}

//wait if needed

async function wait(time) {

    return new Promise(function(resolve) {

        setTimeout(resolve, time)

});

}

Click here to learn to execute puppeteer example using typescript


All Chapters
Author