Select a dropdown option
Choose options in a native select by value, label, or index, handle multi-selects, and drive custom dropdowns.
A native <select> uses selectOption(). A custom dropdown built from div and li elements does not, so you drive it with the same clicks a user makes. Know which one you are looking at before you write the step.
Select from a native dropdown
By default selectOption() matches the option value.
$page->getByLabel('Country')->selectOption('fr');
To be explicit about how you match, pass an option array. Each form targets a different attribute:
$page->getByLabel('Country')->selectOption(['value' => 'fr']);
$page->getByLabel('Country')->selectOption(['label' => 'France']);
$page->getByLabel('Country')->selectOption(['index' => 2]);
selectOption() returns the list of selected values, so you can assert on what was chosen.
Select multiple options
For a <select multiple>, pass an array. Entries can be plain strings or option arrays.
$page->getByLabel('Toppings')->selectOption(['olives', 'cheese']);
The call replaces the current selection with exactly the options you pass.
Drive a custom dropdown
A non-native dropdown has no <option> elements, so selectOption() cannot match anything. Open it with a click, then pick the entry by its option role.
$page->getByRole('button', ['name' => 'Assignee'])->click();
$page->getByRole('option', ['name' => 'Ada Lovelace'])->click();
expect($page->getByRole('button', ['name' => 'Assignee']))->toContainText('Ada Lovelace');
Pitfalls
selectOption()on a custom widget fails because there is no real<select>to act on. Inspect the DOM before choosing the strategy.- Matching by
indexis brittle when the option order changes. Prefervalueorlabel.
Expected result
The native select returns the selected value, or the custom dropdown displays the chosen label. Assert the selected state before submitting a form that depends on it.