Testing an autocomplete

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']);
The typed text is wrapped in <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");
"Searching…" shows for less than half a second. An assertion checks the page at intervals and can miss a state that short. To test a loading state, hold the response in your route handler until you have asserted it.

Country Search

Selected country: None

City Search

Type at least two letters. Suggestions come from the server.

Selected city: None