Back to All Questions
Question 30 of 100
Mechanics
Intermediate
How to handle dynamic elements that appear unpredictably?
The Answer
Use Web-First assertions like `expect(locator).toBeVisible()` which automatically retry until the element appears (within the timeout). For specific conditions, use `locator.waitFor({ state: 'visible' })`.
Deep Dive Explanation
Never use `page.waitForTimeout()` (sleep) for dynamic elements β it creates slow, brittle tests. Web-First assertions are the correct pattern: they retry every 100ms until the condition is met or the timeout expires.
example.spec.ts
// Web-First assertion auto-retries until element appears
await expect(page.getByText('Success! Order placed.')).toBeVisible({ timeout: 10000 });
// Wait for a specific state explicitly
await page.locator('.toast-notification').waitFor({ state: 'visible' });
await page.locator('.loading-spinner').waitFor({ state: 'hidden' });
// Poll for dynamic content
await expect(page.locator('.data-table')).toHaveCount(10, { timeout: 15000 });