Commit b85cb4d0 authored by Đỗ Gia Hưng's avatar Đỗ Gia Hưng

Rewrite HandleJavascriptExecutorTest and HandleWaitTest with practical scenarios

parent 14cc4546
...@@ -4,41 +4,68 @@ import com.automation.base.BaseSetup; ...@@ -4,41 +4,68 @@ import com.automation.base.BaseSetup;
import org.openqa.selenium.By; import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement; import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.Test; import org.testng.annotations.Test;
public class HandleJavascriptExecutorTest extends BaseSetup { public class HandleJavascriptExecutorTest extends BaseSetup {
@Test(priority = 1, description = "Bài 14: Sử dụng JS để Click và Scroll") @Test(priority = 1, description = "Bài 14 - Kịch bản 1: Ép nhập text bằng JS (Vượt thuộc tính readonly/disabled)")
public void testJavascriptExecutorActions() throws InterruptedException { public void testForceSendKeysJS() throws InterruptedException {
driver.get("https://anhtester.com/"); // Sử dụng trang CRM chuẩn của Anh Tester
driver.get("https://cms.anhtester.com/login");
JavascriptExecutor js = (JavascriptExecutor) driver; JavascriptExecutor js = (JavascriptExecutor) driver;
// 1. Lấy Title của trang bằng JS WebElement emailInput = driver.findElement(By.id("email"));
String title = (String) js.executeScript("return document.title;");
System.out.println("Title via JS: " + title); // Gán giá trị bằng JS. Cực kỳ hiệu quả nếu ô input bị thuộc tính readonly chặn.
System.out.println(">>> [Thực chiến] Gán giá trị bằng Javascript để bypass giao diện...");
js.executeScript("arguments[0].value = 'admin@example.com';", emailInput);
// Kiểm tra lại xem đã gán thành công chưa
String actualValue = (String) js.executeScript("return arguments[0].value;", emailInput);
System.out.println(">>> Giá trị ô email sau khi dùng JS: " + actualValue);
Assert.assertEquals(actualValue, "admin@example.com");
// 2. Cuộn chuột xuống cuối trang
System.out.println(">>> Đang cuộn xuống cuối trang...");
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Thread.sleep(2000); Thread.sleep(2000);
}
@Test(priority = 2, description = "Bài 14 - Kịch bản 2: Click bằng JS (Xử lý lỗi ElementClickIntercepted)")
public void testForceClickJS() throws InterruptedException {
driver.get("https://cms.anhtester.com/login");
JavascriptExecutor js = (JavascriptExecutor) driver;
// Xóa email và password mặc định nếu có (trang CRM thường điền sẵn)
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("password")).clear();
WebElement loginBtn = driver.findElement(By.xpath("//button[normalize-space()='Login']"));
// Giả sử nút Login bị popup chặn, click() thường sẽ lỗi. Ta dùng JS.
System.out.println(">>> [Thực chiến] Dùng lệnh click của DOM để xuyên thủng vật cản...");
js.executeScript("arguments[0].click();", loginBtn);
// 3. Cuộn chuột lên đầu trang
System.out.println(">>> Đang cuộn lên đầu trang...");
js.executeScript("window.scrollTo(0, 0)");
Thread.sleep(2000); Thread.sleep(2000);
// 4. Tìm và cuộn đến một element cụ thể // Vì chưa nhập thông tin nên không thể login thành công, URL vẫn giữ nguyên
WebElement blogMenu = driver.findElement(By.xpath("//a[contains(text(),'Blog')]")); String currentUrl = driver.getCurrentUrl();
System.out.println(">>> Đang cuộn đến menu Blog..."); Assert.assertTrue(currentUrl.contains("login"), "Đáng lẽ không thể login nhưng lại thành công!");
js.executeScript("arguments[0].scrollIntoView(true);", blogMenu); }
highlightElement(blogMenu);
@Test(priority = 3, description = "Bài 14 - Kịch bản 3: Cuộn trang phức tạp (Kích hoạt Lazy load)")
public void testScrollJS() throws InterruptedException {
driver.get("https://anhtester.com/");
JavascriptExecutor js = (JavascriptExecutor) driver;
// Cuộn xuống tận cùng trang web
System.out.println(">>> [Thực chiến] Cuộn cật lực xuống cuối trang để ép web load thêm dữ liệu...");
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Thread.sleep(2000); Thread.sleep(2000);
// 5. Click vào element bằng JS (Hữu ích khi element bị che khuất) // Cuộn ngược lên bằng tọa độ (scrollBy)
System.out.println(">>> Đang Click vào menu Blog bằng JS..."); System.out.println(">>> Cuộn ngược lên trên một chút...");
js.executeScript("arguments[0].click();", blogMenu); js.executeScript("window.scrollBy(0, -1500)");
Thread.sleep(2000); Thread.sleep(2000);
} }
} }
...@@ -2,8 +2,11 @@ package com.automation.testcases; ...@@ -2,8 +2,11 @@ package com.automation.testcases;
import com.automation.base.BaseSetup; import com.automation.base.BaseSetup;
import org.openqa.selenium.By; import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement; import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.Test; import org.testng.annotations.Test;
...@@ -12,35 +15,47 @@ import java.time.Duration; ...@@ -12,35 +15,47 @@ import java.time.Duration;
public class HandleWaitTest extends BaseSetup { public class HandleWaitTest extends BaseSetup {
@Test(priority = 1, description = "Bài 15: Sử dụng Explicit Wait (WebDriverWait)") @Test(priority = 1, description = "Bài 15 - Kịch bản 1: Explicit Wait chờ Loading Spinner biến mất")
public void testExplicitWait() { public void testWaitSpinnerDisappear() {
driver.get("https://anhtester.com/login"); driver.get("https://the-internet.herokuapp.com/dynamic_loading/1");
// Khởi tạo WebDriverWait (Chờ tối đa 10 giây) // Click nút Start để hệ thống bắt đầu xử lý (hiện spinner)
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.findElement(By.xpath("//button[text()='Start']")).click();
// 1. Chờ cho tiêu đề trang chứa từ khóa cụ thể WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
wait.until(ExpectedConditions.titleContains("Login | Anh Tester Blog"));
System.out.println(">>> Title đã sẵn sàng.");
// 2. Chờ cho element Login button hiển thị và có thể click được // NẾU DÙNG IMPLICIT WAIT HOẶC THREAD.SLEEP Ở ĐÂY SẼ RẤT DỞ.
WebElement loginBtn = wait.until(ExpectedConditions.elementToBeClickable(By.id("btn-login"))); // Ta BẮT BUỘC dùng Explicit Wait để chờ cái spinner <div id='loading'> mất đi hoàn toàn.
highlightElement(loginBtn); // Đây là tình huống cực kỳ phổ biến khi làm dự án thực tế.
System.out.println(">>> [Thực chiến] Đang chờ Loading Spinner biến mất hoàn toàn...");
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading")));
System.out.println(">>> Nút Login đã sẵn sàng để Click (không dùng Thread.sleep)."); // Sau khi spinner biến mất thì chữ Hello World mới thực sự hiển thị
Assert.assertTrue(loginBtn.isDisplayed()); WebElement finishText = driver.findElement(By.id("finish"));
System.out.println(">>> Kết quả: " + finishText.getText());
Assert.assertTrue(finishText.isDisplayed(), "Dữ liệu chưa load xong!");
} }
@Test(priority = 2, description = "Bài 15: Chờ một element biến mất hoặc xuất hiện") @Test(priority = 2, description = "Bài 15 - Kịch bản 2: Fluent Wait chờ Element ngẫu nhiên")
public void testWaitVisibility() { public void testFluentWait() {
driver.get("https://anhtester.com/"); driver.get("https://the-internet.herokuapp.com/dynamic_loading/2");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.findElement(By.xpath("//button[text()='Start']")).click();
// Chờ cho Logo xuất hiện // Khởi tạo Fluent Wait: Chờ tối đa 15s, cứ 1s tìm 1 lần, bỏ qua lỗi NoSuchElementException
WebElement logo = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='logo']//img"))); FluentWait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(15))
.pollingEvery(Duration.ofSeconds(1))
.ignoring(NoSuchElementException.class);
System.out.println(">>> Logo đã hiển thị: " + logo.getAttribute("src")); System.out.println(">>> [Thực chiến] Đang dùng Fluent Wait để thăm dò sự xuất hiện của phần tử...");
Assert.assertTrue(logo.isDisplayed());
// Element ở trang số 2 này ban đầu hoàn toàn KHÔNG CÓ TRONG DOM.
// Phải dùng FluentWait để nó lặp lại việc tìm kiếm mà không văng lỗi sảng.
WebElement finishText = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='finish']/h4")));
System.out.println(">>> Đã tìm thấy! Kết quả: " + finishText.getText());
Assert.assertEquals(finishText.getText(), "Hello World!");
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment