# 5.12. Wait for loading

Loading là một trong những sự kiện mà khi làm việc với các trang web mình phải tìm cách làm việc với nó, tránh việc này ảnh hưởng test flow.

Selenium có 3 cách waits:

* implicit wait hay là chờ cứng theo một mốc thời gian nhất định.
* explicit wait hay chờ mềm sử dụng trạng thái của một đối tượng hay một trang web để chở trong một khoảng thời gian nhất định. Việc sử dụng explcit giúp linh hoạt trong thì thực thi kiểm thử tự động trong các điều kiện mạng nhanh chậm khác nhau hoặc trạng thái của các đối tượng thay đổi liên tục
* fluent wait - đây là một cải tiến của explicit wait với nhiều điều kiện hơn

Đối với những  dùng selenium hiện nay thường dùng `explicit wait`. Thông qua test case dưới đây mình cho mọi ngừoi hiểu rõ hơn cách dùng `explicit wait`

#### Test case

*Steps*

* Open browser
* Navigate to `https://the-internet.herokuapp.com/dynamic_loading/1`
* Click on Start button
* Wait process bar disappear
* Check finish message

#### Test case as code

```java
@Test 
void dynamicLoadingPage() { 
    WebDriver driver = new ChromeDriver(); 
    driver.get("https://the-internet.herokuapp.com/dynamic_loading/1");
    driver.findElement(By.xpath("//button[.='Start']")).click();

    WebDriverWait wait = new WebDriverWait(driver, 30);
    String finishLbl = wait.until(
            ExpectedConditions
                    .visibilityOfElementLocated(
                            By.id("finish")))
            .getText();

    Assert.assertEquals(finishLbl,"Hello World!");
}
```

#### More ...

* Để có thể sử dụng explicit wait đầu tiên mình cần khởi tạo một biến `wait`:

```java
WebDriverWait wait = new WebDriverWait(driver, 30);
```

* Ở đây mình đưa vào 2 biến là `driver` và `Maximum timeout in seconds = 30`
* Class `ExpectedConditions` cho chúng ta nhiều phương thức khác để chờ đối tượng. `visibilityOfElementLocated`: chờ đối tượng hiển thị trông DOM và trên UI.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tvn.gitbook.io/selenium-java/examples/wait-for-loading.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
