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.
For example, here's how you can start typing a spoken language ("en" for "English") and select the autocompleted option to complete the action:
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
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.