Explicit Waits and Retry Logic
What you'll learn: How to write reliable UI tests that gracefully handle asynchronous updates instead of guessing with arbitrary delays.
The Problem with Sleeping
When you tell a test to sleep(5) (wait 5 seconds), you're making a blind guess. Maybe the UI updates in 1 second—now you're wasting 4 seconds on every test run. Or maybe it takes 6 seconds on a slow CI server—now your test randomly fails.
Think of it like waiting for a pizza delivery: You could stare at the door for exactly 30 minutes (arbitrary sleep), but the pizza might arrive in 10 minutes or 45 minutes. Smarter approach? Keep checking the delivery tracker and act the moment it says "delivered."
How Explicit Waits Work
Explicit waits repeatedly check for a specific condition until it's true (or a timeout occurs). You define what you're waiting for, not just how long to wait.
Instead of:
- "Wait 3 seconds, then click the button" (might not be ready yet)
You do:
- "Wait until the button is clickable, then click it" (responds to actual UI state)
Common Wait Conditions
- Element becomes visible
- Element becomes clickable
- Text appears on the page
- Element disappears (loading spinner gone)
- Attribute changes to expected value
Most UI testing frameworks provide explicit wait mechanisms that poll at small intervals (like checking every 500ms) until your condition passes or the maximum timeout is reached.
Retry Logic
Complementary to waits, retry logic wraps flaky operations: if clicking fails once, try again a few times before declaring failure. This handles momentary glitches without making the entire test unreliable.
Key Takeaway: Replace arbitrary sleeps with explicit waits for specific conditions—your tests become both faster (no unnecessary waiting) and more reliable (they respond to actual UI readiness rather than fixed timeframes).