Convert Hard Sleeps to Auto-Waiting Expects
Reads a test using hard waits and returns a rewritten version using Playwright auto-waiting (`expect(locator).toBeVisible()`, `toHaveText()`, `toHaveCount()`): justifies each replacement by what state the original was waiting for, preserves the test's intent.
When to use it
- Eliminating `waitForTimeout` calls in a Playwright suite to reduce flake.
- Migrating Selenium / Cypress tests (which often have hard sleeps) into Playwright.
- Standardizing wait patterns across a team that varies in approach.
- Onboarding engineers to auto-waiting: the rewrite teaches the pattern.
The prompt
<role>You are a Playwright engineer who has eliminated thousands of hard sleeps. You know that every `waitForTimeout` was waiting for SOMETHING, a render, an animation, an API response, and you map each one to its event-driven replacement.</role> <context>Playwright auto-waiting patterns:- **Visibility**: `expect(locator).toBeVisible()`: waits for element to be in DOM and visible- **Hidden**: `expect(locator).toBeHidden()`: waits for element to disappear- **Text content**: `expect(locator).toHaveText('...')`: waits for text match- **Count**: `expect(locator).toHaveCount(N)`: waits for N elements- **URL**: `await page.waitForURL('/dashboard')`: waits for navigation- **Network**: `await page.waitForResponse(url => ...)`: waits for specific response- **Custom**: `await page.waitForFunction(() => ...)`: for the rare case nothing else fits Each hard sleep was waiting for ONE of these. Identify which, and replace.</context> <task>For the test code below:1. Identify each `waitForTimeout` call.2. Determine what STATE the original was waiting for (visible element, hidden element, text change, URL change, API response).3. Replace with the corresponding auto-waiting pattern.4. Preserve the surrounding logic and assertions unchanged.5. Add a brief comment on EACH replacement explaining the intent (helps future reviewers understand the why).6. Note any case where intent is unclear: recommend asking the original author rather than guessing.</task> <input>Test code with hard sleeps: {test_code}Surrounding context (what the test verifies): {context}</input> <constraints>- Replace EVERY `waitForTimeout` (or sleep equivalent): no remainders.- Prefer web-first assertions (`await expect(locator).toBeVisible()`, `toHaveText`, `toHaveURL`) over `locator.waitFor()` + a one-shot check: they wait and assert in one step.- Add a comment per replacement: `// waits for X (was waitForTimeout)`.- Preserve intent: if the original waited for a debounce, replace with appropriate event observation, not a different sleep.- Acknowledge if intent is ambiguous; recommend asking the author.</constraints> <output_format>Two code blocks:1. **Original (with line numbers)**: annotated to show each hard sleep2. **Rewritten**: full file with each sleep replacedFollowed by a "Justification" section listing each replacement (Line | Was | Now | Why).</output_format> <approach>Before writing, scan the surrounding context of each sleep to identify what it was waiting for.</approach>## RolePlaywright engineer. Every waitForTimeout was waiting for SOMETHING. Map each to event-driven replacement. ## ContextAuto-waiting:- expect(locator).toBeVisible(): element in DOM + visible- toBeHidden(): element disappears- toHaveText('...'): text match- toHaveCount(N): N elements- page.waitForURL('/...'): navigation- page.waitForResponse(url => ...): specific response- page.waitForFunction(() => ...): fallback Each hard sleep waits for ONE of these. ## Task1. Identify each waitForTimeout call.2. Determine what STATE the original was waiting for.3. Replace with auto-waiting pattern.4. Preserve surrounding logic.5. Comment per replacement.6. Acknowledge ambiguous intent: ask author. ## Input- Test code: {test_code}- Surrounding context: {context} ## Constraints- Replace EVERY hard wait: no remainders.- Prefer web-first `expect(...)` assertions over `locator.waitFor()` + one-shot checks.- Comment per replacement.- Preserve intent.- Acknowledge ambiguity. ## Output format2 code blocks (Original annotated | Rewritten) + Justification section (Line | Was | Now | Why). ## ApproachScan surrounding context per sleep: identify what it was waiting for.Example
Input
Test code with hard sleeps:
```typescript
test('checkout flow with discount', async ({ page }) => {
await page.goto('/cart');
await page.waitForTimeout(2000); // wait for cart to load
await page.click('#apply-discount-btn');
await page.waitForTimeout(1500); // wait for discount input to slide in
await page.fill('#discount-code', 'SAVE20');
await page.click('#apply-btn');
await page.waitForTimeout(2500); // wait for discount to be applied
await page.click('#checkout-btn');
await page.waitForTimeout(3000); // wait for redirect to payment
expect(page.url()).toContain('/payment');
});
```
Surrounding context: Cart page has 3 items totalling $100. Applying SAVE20 should reduce subtotal by $20. Clicking checkout redirects to /payment page.Output
## Original (annotated)
```typescript
test('checkout flow with discount', async ({ page }) => {
await page.goto('/cart');
await page.waitForTimeout(2000); // (line 3) waits for cart to render after navigation
await page.click('#apply-discount-btn');
await page.waitForTimeout(1500); // (line 5) waits for discount input to slide in (animation)
await page.fill('#discount-code', 'SAVE20');
await page.click('#apply-btn');
await page.waitForTimeout(2500); // (line 8) waits for discount to be applied (API call + UI update)
await page.click('#checkout-btn');
await page.waitForTimeout(3000); // (line 10) waits for redirect to /payment
expect(page.url()).toContain('/payment');
});
```
## Rewritten
```typescript
test('checkout flow with discount', async ({ page }) => {
await page.goto('/cart');
// waits for cart items to render (was waitForTimeout(2000))
await expect(page.locator('.cart-item').first()).toBeVisible();
await page.click('#apply-discount-btn');
// waits for discount input to slide in and be ready (was waitForTimeout(1500))
await expect(page.locator('#discount-code')).toBeVisible();
await page.fill('#discount-code', 'SAVE20');
await page.click('#apply-btn');
// waits for discount to be applied: UI shows discount line and subtotal updates (was waitForTimeout(2500))
await expect(page.locator('[data-testid="discount-applied"]')).toBeVisible();
await expect(page.locator('[data-testid="subtotal"]')).toHaveText('$80.00');
await page.click('#checkout-btn');
// waits for navigation to /payment (was waitForTimeout(3000)) and asserts it
await expect(page).toHaveURL(/\/payment/);
});
```
## Justification
| Line | Was | Now | Why |
|------|-----|-----|-----|
| 3 | `waitForTimeout(2000)` | `expect(page.locator('.cart-item').first()).toBeVisible()` | The original was waiting for cart items to render; auto-waiting on the first cart item achieves the same intent and adapts to actual render time. |
| 5 | `waitForTimeout(1500)` | `expect(discount-code).toBeVisible()` | Original was waiting for the slide-in. `fill()` already auto-waits for the input to be visible, enabled and editable, and the following `click()` waits for its target to stop moving; the explicit expect documents the intent and gives a clear failure message. |
| 8 | `waitForTimeout(2500)` | `expect(discount-applied).toBeVisible() + expect(subtotal).toHaveText('$80.00')` | Original waited for "discount applied". The behavior under test IS the subtotal updating; the combined check verifies both the visual indication AND the actual computed result. Stronger than the original. |
| 10 | `waitForTimeout(3000)` + `expect(page.url())` | `await expect(page).toHaveURL(/\/payment/)` | One web-first assertion both waits for the redirect and checks it; the old one-shot `expect(page.url())` could read the URL before navigation finished. |
**Coverage note:** All 4 hard sleeps replaced. The test now adapts to actual system speed (faster on local, slower on CI) and includes a stronger behavioral assertion (the subtotal text check at line 8 was previously implicit / untested).Common pitfalls
- Model replaces hard sleeps with `locator.waitFor()` plus a one-shot check such as `expect(await x.count())`: the one-shot part never retries, so races stay. Force web-first `await expect(locator).toBeX()` assertions.
- Replacement loses intent: e.g., 'wait for animation' becomes a visibility check that fires mid-animation.
- Test runs faster after refactor and exposes existing race conditions that the hard sleeps were masking. Surface this as known risk.
- Multiple sleeps for the same condition get replaced individually instead of consolidated.
Tips
- Run the rewritten test 20 times locally to ensure stability: replacing sleeps sometimes reveals masked flake.
- If a sleep is replaced with `waitForResponse`, ensure the URL/method matches exactly: partial matches cause false-positive 'waits'.
- Pair with `review-test-code-anti-patterns` to catch hard sleeps you missed; this prompt operates on known sleeps.
- After the refactor, REMOVE the comment about "was waitForTimeout" once the team is comfortable: clutter.
FAQ
When is `waitForTimeout` legitimately the right answer?
Rare. Almost the only case: waiting for a fixed-duration debounce where no observable side effect signals completion. Even then, prefer `waitForFunction` checking the underlying state. `waitForTimeout` is almost never the right answer.
Cypress equivalents?
Cypress retries auto by default on most commands. Use `cy.get(...).should('be.visible')`: Cypress retries the .should until the condition holds or the timeout expires. Same intent as Playwright auto-waiting.
Dealing with animations?
Three options: (a) wait for the post-animation state (element visible + focused, or content visible), (b) disable animations in test mode via CSS (`*, *::before, *::after { animation-duration: 0s !important; transition-duration: 0s !important; }`), (c) wait for the animation's specific 'transitionend' event.
What if the rewrite reveals existing flakes?
Good: those flakes existed; the sleeps were masking them. Address one at a time. Use `refactor-flaky-test` to identify root cause per flake.