Flaky tests sometimes pass and sometimes fail without code changes. What is the main cause of flaky tests in Selenium?
Think about timing issues and page loading.
Flaky tests often happen when Selenium tries to interact with elements before they are fully loaded or ready. This causes intermittent failures.
Consider this Python Selenium code snippet:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) element = wait.until(EC.visibility_of_element_located((By.ID, "submit"))) print(element.is_displayed())
What will this print if the element with ID 'submit' becomes visible within 10 seconds?
Look at what visibility_of_element_located waits for.
The wait pauses until the element is visible or timeout. If visible, element.is_displayed() returns True.
You want to assert that a message element contains the exact text 'Success'. Which assertion is best to avoid flaky failures due to timing?
message = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.ID, 'msg'))) # Which assertion below is best?
Consider both visibility and exact text match.
Checking visibility and exact text ensures the element is ready and text is correct, reducing flaky failures.
This Selenium test intermittently fails with ElementNotInteractableException. What is the likely cause?
driver.find_element(By.ID, 'login').click() password = driver.find_element(By.ID, 'password') password.send_keys('mypassword')
Think about element readiness before interaction.
Without waiting, the password field might not be ready, causing the exception.
Choose the synchronization approach that most reliably prevents flaky tests caused by timing issues.
Consider flexibility and reliability of waits.
Explicit waits wait for specific conditions and are more reliable than implicit waits or fixed delays, preventing flaky tests effectively.