Waits in Selenium: Implicit, Explicit and Fluent
Web pages load in pieces. If your test clicks a button before it exists, Selenium throws NoSuchElementException. Most "flaky" tests are really timing problems, and waits fix them.
Do not use Thread.sleep
Thread.sleep(5000); // bad
A fixed sleep is either too short (the test fails on a slow day) or too long (every run wastes time). Use a wait that continues as soon as the condition is true.
Implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
Applies to every findElement: Selenium keeps looking for up to 5 seconds. It only waits for an element to exist, not to be visible or clickable. Do not mix it with explicit waits, because the timeouts add up in confusing ways.
Explicit wait (use this)
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
button.click();
wait.until(ExpectedConditions.urlContains("/practice/account/"));
wait.until(ExpectedConditions.textToBePresentInElementLocated(
By.cssSelector("[data-testid='account-name']"), "Demo Tester"));
The conditions you will use most
| Condition | Use it when |
|---|---|
visibilityOfElementLocated | You want to read or check an element. |
elementToBeClickable | You are about to click. |
invisibilityOfElementLocated | A spinner or loader must disappear first. |
textToBePresentInElementLocated | Text changes after an action, such as a status message. |
urlContains / titleIs | You expect a new page. |
alertIsPresent | A JavaScript alert should appear. |
numberOfElementsToBe | A list or table should have a certain number of rows. |
Fluent wait
An explicit wait where you also choose how often to check and which errors to ignore:
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(15))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
WebElement result = wait.until(d -> d.findElement(By.id("result")));
Put waits inside helper methods
Instead of writing a wait before every click, wrap it once:
protected void click(By locator) {
wait.until(ExpectedConditions.elementToBeClickable(locator)).click();
}
protected void type(By locator, String text) {
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
el.clear();
el.sendKeys(text);
}
You will put these helpers in a BasePage in lesson 8.
All 9 lessons in Selenium with Java
- What Is Selenium WebDriver?
- Set Up Java, Maven and Selenium
- Write Your First Selenium Test
- Selenium Locators: ID, CSS, XPath and More
- Clicks, Typing, Dropdowns, Alerts, Frames and Windows
- Waits in Selenium: Implicit, Explicit and Fluent
- TestNG for Selenium: Annotations, Assertions and Data
- Page Object Model in Selenium Java
- Selenium Framework Structure, Reports and CI