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

Thuc hanh xu ly Element va Javascript

parent 69c5e582
package com.automation.testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.time.Duration;
public class WebElementCommandsTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
driver.manage().window().maximize();
// Cài đặt chờ ngầm định 10s cho việc tìm kiếm element
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
}
@Test
public void testFindAndInteractWithElements() throws InterruptedException {
// Mở trang CRM demo của Anh Tester
driver.get("https://crm.anhtester.com/admin/authentication");
System.out.println("Đã mở trang đăng nhập CRM");
// 1. CHUẨN MỰC: TÌM ELEMENT VÀ TƯƠNG TÁC (Check Locator)
// Tìm ô Email qua ID và điền chữ
WebElement inputEmail = driver.findElement(By.id("email"));
inputEmail.clear();
inputEmail.sendKeys("admin@example.com");
// Tìm ô Password qua ID và điền chữ
WebElement inputPassword = driver.findElement(By.id("password"));
inputPassword.clear();
inputPassword.sendKeys("123456");
Thread.sleep(2000); // Tạm dừng 2s để bạn nhìn thấy chữ được điền vào
// 2. NÂNG CAO: DÙNG EXPLICIT WAIT (Chờ đợi thông minh)
// Đợi cho đến khi nút Login sẵn sàng để click (tối đa đợi 10s)
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement buttonLogin = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@type='submit']")));
// 3. NÂNG CAO: DÙNG JAVASCRIPT ĐỂ CLICK NGẦM (Xử lý khi bị che khuất)
// Thông thường bạn chỉ cần gõ: buttonLogin.click();
// Nhưng ở đây ta dùng thử JS để click xuyên qua mọi chướng ngại vật
System.out.println("Thực hiện click nút Login bằng JavascriptExecutor...");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", buttonLogin);
Thread.sleep(3000); // Chờ 3s để bạn quan sát kết quả trang sau khi bấm Đăng nhập
System.out.println("Thực thi kịch bản thành công!");
}
@AfterMethod
public void tearDown() {
if (driver != null) {
driver.quit(); // Đóng trình duyệt dọn dẹp RAM
}
}
}
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