Rafał
Rafał

Reputation: 13

How to avoid repeating Thread.sleep() in selenium test?

I'm writing some test in Selenium and I've got one, annoying problem. In my code Thread.sleep repeats in every second line because I need a short sleep after every function in method. How to avoid it. I don't like my code. It looks very sloppily. I wanna change this repeating Thread.sleep for something more optimal. Here is my code:

@Test
public void shouldDownloadDriver() throws InterruptedException{

    driver.get("https://www.selenium.dev/");
    driver.manage().window().maximize();
    Thread.sleep(1500);
    driver.findElement(By.xpath("//*[@id=\"main_navbar\"]/ul/li[4]/a/span")).click();
    Thread.sleep(1500);
    driver.findElement(By.xpath("//*[@id=\"m-documentationgetting_started\"]/span")).click();
    Thread.sleep(1500);
    driver.findElement(By.xpath("//*[@id=\"m-documentationgetting_startedinstalling_browser_drivers\"]/span")).click();
    Thread.sleep(1500);
    ((JavascriptExecutor) driver).executeScript("window.open()");
    ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());

    driver.switchTo().window(tabs.get(1));
    driver.get("https://chromedriver.storage.googleapis.com/index.html");
    Thread.sleep(1500);
    driver.findElement(By.xpath("/html/body/table/tbody/tr[100]/td[2]/a")).click();
    Thread.sleep(1500);
    driver.findElement(By.xpath("/html/body/table/tbody/tr[4]/td[2]/a")).click();
    Thread.sleep(2000);
    driver.switchTo().window(tabs.get(0));
    Thread.sleep(3000);
    printSuccess();
}

Upvotes: 1

Views: 690

Answers (1)

Nandan A
Nandan A

Reputation: 2922

visibilityOfElementLocated: Returns the WebElement once it is located and visible.

  • An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.
    WebDriverWait wait = new WebDriverWait(driver,10);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"main_navbar\"]/ul/li[4]/a/span")));
    driver.findElement(By.xpath("//*[@id=\"main_navbar\"]/ul/li[4]/a/span")).click();

presenceOfElementLocated: Returns the WebElement if element is present on DOM and not even visible.

  • An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.
    WebDriverWait wait = new WebDriverWait(driver,10);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"main_navbar\"]/ul/li[4]/a/span")));
    driver.findElement(By.xpath("//*[@id=\"main_navbar\"]/ul/li[4]/a/span")).click();

Upvotes: 1

Related Questions