About Testing Single-selection Autocomplete Fields with Selenium
Selenium allows testing not only the common input fields, but also autocomplete fields, such as this single-selection autocomplete field built with django-autocomplete-light.
For example, here's how you can start typing a country ("germ" for "Germany") 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/")
# activate the dropdown with the search field
browser.find_element(
by=By.CSS_SELECTOR, value="#div_id_country .select2-selection"
).send_keys("\n")
search_field = WebDriverWait(browser, 10).until(
EC.presence_of_element_located(
(By.CSS_SELECTOR, "body>.select2-container input.select2-search__field")
)
)
# type a few letters and press ENTER
search_field.send_keys("germ\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.