In this example we will see how to automate auto-suggest dropdown using Playwright. auto-suggest dropdowns — These are typically not native <select> elements and usually get rendered as you type (think Google Search, React Autocomplete, etc.). So you’ll need to interact with them like regular DOM elements.
Understanding Auto-Suggest dropdown in playwright
An auto-suggest dropdown is a dynamic interface element that displays a list of suggestions as users type into an input field. This functionality is common in search fields. The suggestions can change based on the input, making it essential to handle them dynamically in automated tests.
✅ Basic steps to work with autocomplete dropdown.
1. Type into the input box
await page.fill('#search-box', 'Ba'); // Typing triggers suggestions2. Wait for suggestions to appear
await page.waitForSelector('.suggestion-item'); // Or use a more specific selector
3. Select an option by text
await page.click('text=Banana');
Example for Autocomplete dropdown
// @ts-check import { test, expect } from '@playwright/test'; test('Handle autocomplete dropdown', async ({page}) => { await page.goto("https://practice.expandtesting.com/autocomplete"); // Fill the input field with a search term await page.locator("#country").fill("ca"); // Wait for the suggestions to appear await page.waitForSelector("#countryautocomplete-list"); // Retrieve all suggested counties const suggestedCountry = await page.$$("#countryautocomplete-list div"); // Loop through suggestions and click on the desired one for (let option of suggestedCountry) { const value = await option.textContent(); if (value.includes("Canada")) { await option.click(); break; // Exit loop after clicking } } //click on submit button await page.locator("//button[contains(text(),'Submit')]").click(); //Check entered value in auto complete dropdown. const getEnteredValue = await page.locator("//p[contains(text(),'You selected: Canada')]").textContent(); expect(getEnteredValue).toEqual("You selected: Canada"); });
Automating interactions with auto-suggest dropdowns using Playwright is straightforward once you understand how to wait for elements and interact with them dynamically.
No comments:
Post a Comment