Flaky tests often guess at timing with arbitrary delays. This creates race
conditions where tests pass on fast machines but fail under load or in CI.
Core principle: Wait for the actual condition you care about, not a guess
about how long it takes.
When to Use
Use when:
Tests have arbitrary delays (sleep, wait, timeout)
Tests are flaky (pass sometimes, fail under load)
Tests timeout when run in parallel
Waiting for async operations to complete
Don't use when:
Testing actual timing behavior (debounce, throttle intervals)
Always document WHY if using arbitrary timeout
Core Pattern
# BEFORE: Guessing at timing
sleep(50)
result = getResult()
assert result is not None
# AFTER: Waiting for condition
waitFor(lambda: getResult() is not None, timeout=5000)
result = getResult()
assert result is not None
async function waitFor(condition, description, timeoutMs=5000):
startTime = currentTime()
while True:
result = condition()
if result:
return result
if currentTime() - startTime > timeoutMs:
raise Error("Timeout waiting for " + description + " after " + timeoutMs + "ms")
sleep(10) # Poll every 10ms
Common Mistakes
Polling too fast:sleep(1) - wastes CPU Fix: Poll every 10ms
No timeout: Loop forever if condition never met Fix: Always include
timeout with clear error
Stale data: Cache state before loop Fix: Call getter inside loop for
fresh data
When Arbitrary Timeout IS Correct
# Tool ticks every 100ms - need 2 ticks to verify partial output
waitForEvent(manager, 'TOOL_STARTED') # First: wait for condition
sleep(200) # Then: wait for timed behavior
# 200ms = 2 ticks at 100ms intervals - documented and justified
Requirements:
First wait for triggering condition
Based on known timing (not guessing)
Comment explaining WHY
Markdown source
# Condition-Based Waiting## OverviewFlaky tests often guess at timing with arbitrary delays. This creates race
conditions where tests pass on fast machines but fail under load or in CI.
**Core principle:** Wait for the actual condition you care about, not a guess
about how long it takes.
## When to Use**Use when:**
- Tests have arbitrary delays (sleep, wait, timeout)
- Tests are flaky (pass sometimes, fail under load)
- Tests timeout when run in parallel
- Waiting for async operations to complete
**Don't use when:**
- Testing actual timing behavior (debounce, throttle intervals)
- Always document WHY if using arbitrary timeout
## Core Pattern```
# BEFORE: Guessing at timing
sleep(50)
result = getResult()
assert result is not None
# AFTER: Waiting for condition
waitFor(lambda: getResult() is not None, timeout=5000)
result = getResult()
assert result is not None
```
## Quick Patterns| Scenario | Pattern |
| ----------------- | ---------------------------------------------------------- |
| Wait for event | `waitFor(lambda: events.find(lambda e: e.type == 'DONE'))` |
| Wait for state | `waitFor(lambda: machine.state == 'ready')` |
| Wait for count | `waitFor(lambda: len(items) >= 5)` |
| Wait for file | `waitFor(lambda: path.exists(path))` |
| Complex condition | `waitFor(lambda: obj.ready and obj.value > 10)` |
## Generic ImplementationGeneric polling function:
```
async function waitFor(condition, description, timeoutMs=5000):
startTime = currentTime()
while True:
result = condition()
if result:
return result
if currentTime() - startTime > timeoutMs:
raise Error("Timeout waiting for " + description + " after " + timeoutMs + "ms")
sleep(10) # Poll every 10ms
```
## Common Mistakes**Polling too fast:** `sleep(1)` - wastes CPU **Fix:** Poll every 10ms
**No timeout:** Loop forever if condition never met **Fix:** Always include
timeout with clear error
**Stale data:** Cache state before loop **Fix:** Call getter inside loop for
fresh data
## When Arbitrary Timeout IS Correct```
# Tool ticks every 100ms - need 2 ticks to verify partial output
waitForEvent(manager, 'TOOL_STARTED') # First: wait for condition
sleep(200) # Then: wait for timed behavior
# 200ms = 2 ticks at 100ms intervals - documented and justified
```
**Requirements:**
1. First wait for triggering condition
2. Based on known timing (not guessing)
3. Comment explaining WHY