UI automation · core
Waits and stale elements in Selenium
A sleep waits a fixed time and is always wrong. Use an explicit wait for the real condition, and find elements again after the page changes.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Thread.sleep(5000) always waits five seconds: too long when the app is fast, too short when it is slow. Replace it with an explicit wait for the real condition.
- Selenium docs say not to mix implicit and explicit waits, because the wait times become unpredictable. Use explicit waits and leave the implicit wait at 0.
- driver.quit() must run in a teardown such as @AfterMethod(alwaysRun = true). If it sits inside the test and an assertion fails first, the browser stays open and CI fills with Chrome processes.
- quit() ends the browser and the driver process. close() closes only one window.
- StaleElementReferenceException means the reference points to a DOM node that was removed or replaced, for example when a filter redraws the list.
- It is a race, so it is intermittent. The fix is to wait for the old element to go stale (ExpectedConditions.stalenessOf) and then find the new one, or wait for a signal such as the loader disappearing.
- Keep By locators in the page object and find the element just before use. Do not keep WebElement objects across actions that change the page.
- A weak assertion such as size() > 0 proves little. Check the content that matters.
The red pen
Common traps: mistake → fix
Mistake: A longer sleep fixes it
Fix: it only hides the race and slows every run.
Mistake: Implicit waits are best for every element
Fix: mixing them with explicit waits gives unpredictable timeouts.
Mistake: Catching StaleElementReferenceException and ignoring it is a fix
Fix: it hides real bugs; find the element again after waiting.
Mistake: A JavaScript click solves a failing click
Fix: it skips the checks a real user would meet.
Easy to hard
Questions interviewers ask, easy to hard
- Why is Thread.sleep a bad wait?
- What is the difference between an implicit and an explicit wait? Can you mix them?
- Why does StaleElementReferenceException happen only sometimes?
- Where should driver.quit() be called, and why?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.