Selecting an Option Using Playwright
On This Page How to Use Playwright selectOption1. By Visib
How to Select an Option Using Playwright
Have you ever tried selecting an option from a dropdown in Playwright and felt like it just wasn & # 8217; t working the way you wait?
I & # 8217; ve be there. When I first automated forms with Playwright, I ran into a few frustrating moments where selectOption didn & # 8217; t behave systematically across different browsers.
Sometimes the improper option got selected, and other times the test failed without a clear ground.
I tried different approaches and explored Playwright & # 8217; s features until I found techniques that make dropdown selections reliable and tests lots more stable.
Overview
let you opt options from a dropdown () using the selectOption () method. You can pick an selection in different agency look on what is easiest for your test.
1. By Visible Text (Label)
Select an option using the text that look in the dropdown:
await page.selectOption (& # 8216; quality # dropdownId & # 8217;, {label: & # 8216; Option 2 & # 8217;});
// or
await page.locator (& # 8216; select # dropdownId & # 8217;) .selectOption ({label: & # 8216; Option 2 & # 8217;});2. By Value Attribute
Use the choice & # 8217; s value attribute, which is usually unique:
await page.selectOption (& # 8216; prize # dropdownId & # 8217;, {value: & # 8216; optionValue & # 8217;});
// or
await page.locator (& # 8216; select # dropdownId & # 8217;) .selectOption ({value: & # 8216; optionValue & # 8217;});3. By Index
Pick an choice based on its position in the list (zero-based):
await page.selectOption (& # 8216; select # dropdownId & # 8217;, {index: 1}); // choose the second option4. Selecting Multiple Options
For multi-select dropdowns (), provide an array of value, label, or indices:
// By values
await page.selectOption (& # 8216; # multiSelect & # 8217;, [& # 8216; value1 & # 8217;, & # 8216; value2 & # 8217;]);
// By labels
await page.selectOption (& # 8216; # multiSelect & # 8217;, [& # 8216; Option 1 & # 8217;, & # 8216; Option 3 & # 8217;]);
// By indices
await page.selectOption (& # 8216; # multiSelect & # 8217;, [{index: 0}, {indicator: 2}]);
In this clause, I & # 8217; ll walking you through how to reliably select pick using Playwright, share the pitfalls I ran into, and show practical tips to create your automation smoother and more predictable.
How to Use Playwright selectOption
Playwright provide the selectOption () method to choose options from a dropdown (). Depending on your test scenario, you can select options by label, value, or index. For multi-select dropdowns, you can take multiple options at once.
1. By Visible Text (Label)
Sometimes the easiest way to select an option is by the text that appear in the dropdown. This is useful when the value dimension is dynamical or unknown, but the visible text is coherent.
await page.selectOption (& # 8216; select # dropdownId & # 8217;, {label: & # 8216; Option 2 & # 8217;});
// or employ locator
await page.locator (& # 8216; select # dropdownId & # 8217;) .selectOption ({label: & # 8216; Option 2 & # 8217;});2. By Value Attribute
Many dropdowns use a value attribute as a alone identifier for each option. Selecting by value ensures that your test act even if the seeable text changes slightly.
await page.selectOption (& # 8216; select # dropdownId & # 8217;, {value: & # 8216; optionValue & # 8217;});
await page.locator (& # 8216; select # dropdownId & # 8217;) .selectOption ({value: & # 8216; optionValue & # 8217;});3. By Index
Sometimes you may want to select an option found on its place in the inclination, especially when neither the label nor value is consistent. Remember that the index is zero-based.
await page.selectOption (& # 8216; select # dropdownId & # 8217;, {index: 1}); // select the second option4. Selecting Multiple Options
For multi-select dropdowns (), you can select several options at once by providing an array of labels, values, or power. This is particularly useful for filters or multi-choice forms.
// By labels
await page.selectOption (& # 8216; # multiSelect & # 8217;, [& # 8216; Option 1 & # 8217;, & # 8216; Option 3 & # 8217;]);
// By value
await page.selectOption (& # 8216; # multiSelect & # 8217;, [& # 8216; value1 & # 8217;, & # 8216; value2 & # 8217;]);
// By indicator
await page.selectOption (& # 8216; # multiSelect & # 8217;, [{index: 0}, {index: 2}]);
Handling Custom or Dynamic Dropdowns
Not all dropdowns are simple & lt; blue-ribbon & gt; element. Many modern web applications use usance dropdowns built with & lt; div & gt;, & lt; ul & gt;, or other HTML structures, often with dynamic options load via or API calls. These dropdowns don ’ t work with selectOption (), so you need a different coming.
1. Clicking to Open and Selecting an Option
For customs dropdowns, the usual method is to snap the dropdown to reveal the options and then tick the option you want.
// Open the dropdown
await page.click (& # 8216; # customDropdown & # 8217;);// Select the craved option
await page.click (& # 8216; text=Option 2 & # 8217;);
2. Using Locators for Dynamic Options
If the options load asynchronously, you should wait for them to seem before take. Playwright & # 8217; s locator with waitFor or initiative can assist:
const option = page.locator (& # 8216; .dropdown-option & # 8217;, {hasText: & # 8216; Option 2 & # 8217;});
await option.waitFor ({state: & # 8216; visible & # 8217;});
await option.click ();3. Handling Multi-Select Custom Dropdowns
For multi-select dropdowns, repeat the click for each desired choice. If the options are dynamic, invariably wait for them to appear to avoid flakey tests:
const options = [& # 8216; Option 1 & # 8217;, & # 8216; Option 3 & # 8217;];
for (const label of options) {
const optionLocator = page.locator (& # 8216; .dropdown-option & # 8217;, {hasText: label});
await optionLocator.waitFor ({province: & # 8216; visible & # 8217;});
await optionLocator.click ();
}
Read More:
SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.
How to Ensure Reliable Option Selection in Playwright
Even when your dropdown locater seems correct, tests can still fail due to timing issues, dynamic content, or browser inconsistencies. To create your pick selection reliable, postdate these best exercise.
1. Wait for the Dropdown to Be Ready
Always control the dropdown is full rendered and visible before interacting. Use Playwright & # 8217; s locator.waitFor () or built-in await check:
const dropdown = page.locator (& # 8216; select # dropdownId & # 8217;); look dropdown.waitFor ({state: & # 8216; visible & # 8217;});
await dropdown.selectOption ({label: & # 8216; Option 2 & # 8217;});2. Use Explicit Locators
Target the element or selection precisely using IDs, classes, or textbook. Avoid generic selectors like select or div that might match multiple elements.
await page.locator (& # 8216; quality # countryDropdown & # 8217;) .selectOption ({value: & # 8216; IN & # 8217;});3. Handle Dynamic or Lazy-Loaded Options
If pick appear after an API call or life, hold for them explicitly before selection:
const pick = page.locator (& # 8216; choice & # 8217;, {hasText: & # 8216; Option 2 & # 8217;}); await option.waitFor ({state: & # 8216; seeable & # 8217;});
await option.click ();Read More:
4. Use Assertions to Confirm Selection
After selecting, always verify the value to get silent failures:
await await (page.locator (& # 8216; select # dropdownId & # 8217;)) .toHaveValue (& # 8216; optionValue & # 8217;);
Also Read:
5. Consider Substitute Approaches for Custom Dropdowns
For non-standard dropdowns (& lt; div & gt;, & lt; ul & gt;, or dynamic components), simulate user interactions:
- Click to open
- Wait for option to appear
- Click the craved choice
await page.click (& # 8216; # customDropdown & # 8217;);
await page.locator (& # 8216; .dropdown-item & # 8217;, {hasText: & # 8216; Option 2 & # 8217;}) .click ();
Even if selectOption () passes on a local machine, dropdown conduct can deviate across real browsers. BrowserStack countenance you try on thousands of devices to assure choice work consistently everywhere.
Troubleshooting Playwright selectOption ()
Even with correct locator and proper waiting, select options in Playwright can sometimes fail. Understanding common issues and their fixes can save a lot of debug time.
1. Dropdown Not Found or Not Seeable
If Playwright can not encounter the element or it is conceal, selectOption () will miscarry. Always ensure the element is present and seeable:
const dropdown = page.locator (& # 8216; select # dropdownId & # 8217;);
await dropdown.waitFor ({state: & # 8216; seeable & # 8217;});
await dropdown.selectOption ({label: & # 8216; Option 2 & # 8217;});
2. Wrong Option Selected
This can befall if the label or value does not tally incisively. Check for leading/trailing spaces, casing, or dynamic values. Using precise strings or trimming input can help:
await dropdown.selectOption ({label: & # 8216; Option 2 & # 8217; .trim ()});3. Multi-Select Misbehaving
For single-select dropdowns, passing multiple alternative will only select the last one. For multi-select dropdowns, guarantee the component has the multiple property:
await page.selectOption (& # 8216; # multiSelect & # 8217;, [& # 8216; Option 1 & # 8217;, & # 8216; Option 3 & # 8217;]); // works alone if
4. Dynamic or Lazy-Loaded Options
If options load asynchronously, the selection may neglect because the pick isn & # 8217; t in the DOM yet. Wait explicitly for the option before selecting:
const selection = page.locator (& # 8216; option & # 8217;, {hasText: & # 8216; Option 2 & # 8217;});
await option.waitFor ({state: & # 8216; visible & # 8217;});
await option.click ();Read More:
5. Custom Dropdowns
selectOption () act only on & lt; prime & gt; elements. For custom dropdowns built with & lt; div & gt; or & lt; ul & gt;, simulate a user click:
await page.click (& # 8216; # customDropdown & # 8217;);
await page.locator (& # 8216; .dropdown-item & # 8217;, {hasText: & # 8216; Option 2 & # 8217;}) .click ();
6. Assertion Failures
Even after pick, tests can neglect if the value doesn & # 8217; t match expectation. Always control with a:
await expect (dropdown) .toHaveValue (& # 8216; optionValue & # 8217;);
Pro Tip:If tests nevertheless fail intermittently, add small hold or use locator.first () for reiterate elements to make selections more stable.
Better Practices for Selecting Options in Playwright
Selecting selection in dropdowns might look simple, but small mistakes can lead to flaky or unreliable tests. Following these best pattern aid ensure your tests are stable, maintainable, and resilient across different browsers and dynamic web environments.
- Use Precise Locators:Always place the dropdown and its options with unique identifiers such as IDs, assort, or accurate text. This prevents inadvertent interactions with similar elements elsewhere on the page and reduces flakiness.
- Wait for Elements to Be Ready:Dropdowns and choice may load asynchronously due to JavaScript or API calls. Ensure that the dropdown and its options are fully seeable and interactable before attempting a selection.
Read More:
- Verify Selections:Confirm that the selected option is applied correctly utilise assertions. This avoids still tryout failure where the test passes, but the wrong option is actually take.
- Consider Multi-Select Scenarios:For multi-select dropdowns, ensure the ingredient supports multiple option and verify each selected option singly. Selecting multiple options in a single-select dropdown will only select the last one.
Also Read:
- Handle Custom or Dynamic Dropdowns Carefully:For non-standard dropdowns built with & lt; div & gt; or & lt; ul & gt; ingredient, simulate existent user interaction by opening the dropdown, waiting for alternative to appear, and snap the desired option. This approach handles dynamic content reliably.
- Keep Tests Readable and Maintainable:Organize repetitive pick logic in helper functions, use descriptive labels or values rather of indexes, and avoid hard-to-read selectors. This makes your test easy to maintain as the coating acquire.
- Avoid Hardcoded Waits:Do not swear on fixed delays (sleep or waitForTimeout) as they can slack examination and still fail unpredictably. Use Playwright & # 8217; s built-in waiting mechanisms to look for profile, enablement, or specific conditions instead.
Read More:
Testing Playwright Select Option on Real Browsers with BrowserStack
Select-option tests usually betray for reasons that do not show up locally. UI frameworks replace the native& lt; select & gt;with custom element, so Playwright interacts with a simulated dropdown rather of a real one. These constituent rely on animations, delayed rendering, or hidden DOM nodes that load at slightly different clip on different browser.
As a result, selectOption () surpass in Chromium but fails in Firefox, selects the wrong item when the list scroll incorrectly, or clicks the overlay rather of the actual pick.
Testing on real browsers can assist uncover these inconsistency. Platforms likeBrowserStacklet you run your Playwright tests across multiple browsers and engines, exposing differences in rendering, event timing, and pore behaviour that local or brainless runs oftentimes miss.
Here is how helps make Playwright tryout more reliable:
- :Run test on thousands of real desktop and mobile browsers to ensure consistent behavior across platforms.
- :Execute multiple Playwright tests at the same time across different browser and devices to race up validation.
- :Access picture transcription, console logarithm, and network tincture to quickly identify and fix issues with dropdown selections or other interactions.
- Support:Securely test local or present environments on real browsers without deploying publically.
- :Integrate with existing grapevine to mechanically run Playwright tests on real browsers during builds and deployment.
Conclusion
Selecting options with Playwright can be tricky when dropdowns are dynamic, multi-select, or custom-styled. Using precise locators, waiting for elements, and validating selections helps ensure reliable and consistent examination.
Running these tests on real browser and devices reveals issues that local tests might lose. Platforms like BrowserStack allow you to validate dropdown interaction across thousands of environments, catch number that local tests might miss, and provide debugging tools such as video recordings and logs to quickly resolve failures.
On This Page
# Ask-and-Contributeabout this topic with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free