lecture 11 of 200 completed

Waiting properly

A fixed sleep is a guess. Selenium makes you wait on purpose, so learn the right way early.

Saving a contact takes about 700 milliseconds. So the obvious thing to write is this:

await driver.findElement(By.css('[data-testid="save-contact"]')).click();
await driver.sleep(1000);
const toast = await driver.findElement(By.css('[data-testid="toast"]'));
assert.ok((await toast.getText()).includes('Contact created'));

Wait one second, then check. It works on your machine. Please do not do it, and here is why.

A fixed sleep is a guess about how long something takes, and you lose that guess in both directions.

When it is too short, the test fails for no real reason. Your laptop is fast. The build server is usually slower and busier.

When it is too long, you pay for it forever. One extra second in eighty tests is more than a minute added to every single run.

Unlike newer tools, Selenium does not wait for conditions by itself. You have to ask. The right way is an explicit wait:

await driver.findElement(By.css('[data-testid="save-contact"]')).click();

const toast = await driver.wait(
  until.elementLocated(By.css('[data-testid="toast"]')),
  5000
);
assert.ok((await toast.getText()).includes('Contact created'));

Read that middle part carefully, because you will write it hundreds of times. driver.wait takes two things: a condition to check, and a maximum time to keep trying. It checks every few hundred milliseconds. The moment the toast appears, it returns it and your test continues.

So if the save takes 200ms, you continue after 200ms. If it takes 3 seconds, you wait 3 seconds. And if the toast never appears, you get a clear error after 5 seconds.

until has several conditions ready for you:

until.elementLocated(By.css('...'))   // it exists in the page
until.elementIsVisible(element)       // the user can see it
until.urlContains('/dashboard')       // navigation finished

Remember this: driver.sleep is a guess. driver.wait is a question. Ask the question.

Reference: Waits.

now prove it

Reading is the setup. Solve these problems in the editor. We break the app on purpose to check your test would catch it.