Autocomplete
Two comboboxes: one filters a list in the browser, the other asks the server as you type.
Type like a user
Suggestions react to key events. fill() sets the value in one go, which most comboboxes handle. When one does not, type with pressSequentially().
Options have a role
The input is a combobox, the list a listbox and each suggestion an option. Assert the whole list at once:
await page.getByRole('combobox', { name: 'Country' }).fill('united');
await expect(page.getByRole('option')).toHaveText(['United Kingdom', 'United States']);<mark> inside each option. toHaveText() reads the text of the whole element, so the extra markup does not matter.Names that repeat
A role name matches part of the text. "Paris" matches both "Paris, France" and "Paris, United States": use the full name with exact: true.
Suggestions from the server
The city search waits until you stop typing (a debounce), then sends one request. Control the answers with page.route(): return fixed cities, nothing, or an error.
await page.route('**/api/cities?*', (route) => route.fulfill({ status: 500 }));
await page.getByRole('combobox', { name: 'City' }).fill('par');
await expect(page.getByRole('alert')).toContainText("Couldn't load suggestions");Country Search
City Search
Type at least two letters. Suggestions come from the server.
Related exercises
- Basic ElementsBeginnerDropdownChoose options from native selects and from a custom dropdown.
- Network & APIAdvancedNetwork MockingControl network responses to test states that are hard to get from a real backend.
- Mouse & KeyboardBeginnerKeyboard ActionsDrive the page with the keyboard alone: typing, Tab order, shortcuts and held keys.
Read the guide: Playwright network mocking and API testing