About Testing Multiple-selection Autocomplete Fields with Selenium

Selenium 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
24
25
26
27
28
29
30
31
32
33
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

chrome_options = Options()
chrome_options.binary_location = settings.CHROME_BINARY_PATH
chrome_options.add_argument("--disable-search-engine-choice-screen")

browser = webdriver.Chrome(
    service=ChromeService(executable_path=settings.CHROME_DRIVER_PATH),
    options=chrome_options,
)
browser.get("https://example.com/message-form/")

search_field = self.browser.find_element(
    by=By.CSS_SELECTOR, value="#div_id_spoken_languages .select2-search__field"
)
# type a few letters
search_field.send_keys("en")
option = WebDriverWait(self.browser, 10).until(
    EC.presence_of_element_located(
        (
            By.XPATH,
            "//li[contains(@class, 'select2-results__option--highlighted') and "
            "contains(text(), 'English')]",
        )
    )
)
# Select that option
search_field.send_keys("\n")

browser.quit()

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 Selenium