javascripttypescriptautomated-testsplaywright

How to select an element from a dropdown menu?


I have a pop-up modal, in which I am creating a rule from, but when trying to select the elements from the select-menu, my test fails. I have this on the web page

<label class="form-label"> Group Granularity </label>
<select class="form-select"> 
<option selected disabled value>Select granularity</option>
<option value="per-metric">per-metric</option>
<option value="per-hostname">per-hostname</option>
<option value="per-group">per-group</option>
<option value="global">global</option>
</select>

I tried a few code options to handle it, but none of them seem to work i.e

await page.getByText('Group Granularity').click();
await page.getByRole('option', { name: 'per-hostname' }).click();

and the error is as follows, because it seems that the element doesn't get identified within the timeout threshold:

Error: locator.click: Test timeout of 30000ms exceeded.

Solution

  • You shouldn't do a manual .click() on an <option>, rather use selectOption provided by playwright:


    Using getByLabel to find your <select>, then you can select an <option> with:

    await page.getByLabel('Group Granularity').selectOption('per-hostname');