JS Testing Academy · QA Demo Site

Alerts

Simple alert, an alert after 5 seconds, a confirm box and a prompt – the four JavaScript dialogs you must know how to handle.

Practice tasks

  1. Click the first button, switch to the alert and accept it.
  2. Click the timer button, wait for the alert with an explicit wait, then accept it.
  3. Accept the confirm box and assert the result reads You selected Ok.
  4. Dismiss the confirm box and assert the result reads You selected Cancel.
  5. Type your name in the prompt and assert the result shows it.
  6. Dismiss the prompt and assert the result says it was cancelled.
Sample automation code
driver.findElement(By.id("alert-button")).click();
driver.switchTo().alert().accept();

driver.findElement(By.id("timer-alert-button")).click();
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();

driver.findElement(By.id("confirm-button")).click();
driver.switchTo().alert().dismiss();
Assert.assertEquals(driver.findElement(By.id("confirm-result")).getText(), "You selected Cancel");

driver.findElement(By.id("prompt-button")).click();
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("Karthik");
prompt.accept();