About Testing Multiple-selection Autocomplete Fields with Playwright

Playwright allows testing not only the common input fields, but also autocomplete fields, such as this multiple-selection autocomplete field built with django-autocomplete-light.

multiple-selection autocomplete field

For example, here's how you can start typing a spoken language ("en" for "English") and select the autocompleted option to complete the action:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from playwright.sync_api import sync_playwright

playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(viewport={"width": 1200, "height": 800})
page = context.new_page()

page.goto("https://example.com/message-form/")
# activate the dropdown with the search field
page.click("#div_id_spoken_languages .select2-search__field")
# type a few letters
page.fill(
    "#div_id_spoken_languages .select2-search__field", 
    "en",
)
# click on the highlighted option
page.locator(
    "li.select2-results__option--highlighted", 
    has_text="English",
).click()

browser.close()
playwright.stop()

Add some time.sleep(1) calls between the actions to slow down the tests and be able to see what's going on visually.

Tips and Tricks Testing Django 5.x Django 4.2 Django 3.2 django-autocomplete-light Playwright