Replace Every Sleep with a Real Wait
beginner JavaScript 15 minA search test is littered with driver.sleep and setTimeout calls. It takes 14 seconds and still fails in CI. Replace each sleep with the condition it was guessing at.
The Scenario
The search test spends 14 seconds sleeping on every run, whether the app is fast or slow. On a busy CI runner the filter request occasionally takes longer than five seconds, so the test reads the old, unfiltered results and fails on expect(items.length).toBe(3).
A teammate’s proposed fix is to raise every sleep to 10 seconds. That would make the test take over 30 seconds and it would still fail on a bad day.
Your Task
Replace each driver.sleep and setTimeout with an explicit wait for the condition the author was actually guessing at. The test should finish as soon as the app is ready and fail with a useful message when it is not.
What Good Looks Like
- Zero sleeps. Every wait has a condition, a timeout and, for custom conditions, a message.
- The re-render is detected by staleness of the old list or by the spinner disappearing, not by elapsed time.
- The result count is waited for, not read once immediately after the click.
- Locators are declared once as constants.
Tip: The same rule applies to AI-generated code. The selenium.dev guidance on AI coding agents says not to let agents “fix” flakiness by adding sleeps. Put that rule in your AGENTS.md or CLAUDE.md.
Your task
A search test is littered with driver.sleep and setTimeout calls. It takes 14 seconds and still fails in CI. Replace each sleep with the condition it was guessing at.
const { By, Key } = require('selenium-webdriver');
it('filters search results', async () => {
await driver.get('https://shop.example.com');
await driver.sleep(3000); // page load
await driver.findElement(By.name('q')).sendKeys('laptop', Key.ENTER);
await new Promise((r) => setTimeout(r, 4000)); // results
await driver.findElement(By.css('[data-testid="filter-brand-acme"]')).click();
await driver.sleep(5000); // re-render
const items = await driver.findElements(By.css('[data-testid="result"]'));
expect(items.length).toBe(3);
await items[0].click();
await driver.sleep(2000); // navigation
expect(await driver.getCurrentUrl()).toContain('/product/');
});
Need Help?
Solution
Try to solve the challenge yourself before revealing the solution.
Lessons that cover this
- Explicit Waits Learn to use explicit waits in Selenium to handle dynamic content and avoid flaky tests.
- Expected Conditions Use built-in expected conditions for common wait scenarios like visibility, clickability, and text presence.
- Flaky Tests: Diagnosis and Cure A systematic method for finding why a test passes sometimes: classify the failure, reproduce it deliberately, fix the root cause (timing, state, order, environment, product), and quarantine without hiding.