撰寫測試
簡介
Playwright 斷言專為動態網頁建立。檢查會自動重試直到滿足必要條件。Playwright 內建自動等待,這意味著它會在執行操作之前等待元素可操作。Playwright 提供assertThat重載來撰寫斷言。
請查看下面的範例測試,了解如何使用 web first 斷言、定位器和選擇器來編寫測試。
package org.example;
import java.util.regex.Pattern;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class App {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("http://playwright.dev");
// Expect a title "to contain" a substring.
assertThat(page).hasTitle(Pattern.compile("Playwright"));
// create a locator
Locator getStarted = page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Get Started"));
// Expect an attribute "to be strictly equal" to the value.
assertThat(getStarted).hasAttribute("href", "/docs/intro");
// Click the get started link.
getStarted.click();
// Expects page to have a heading with the name of Installation.
assertThat(page.getByRole(AriaRole.HEADING,
new Page.GetByRoleOptions().setName("Installation"))).isVisible();
}
}
}
斷言
Playwright 提供了assertThat
多載,將會等待直到預期條件被滿足。
import java.util.regex.Pattern;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
assertThat(page).hasTitle(Pattern.compile("Playwright"));
定位器
定位器 是 Playwright 自動等待和重試功能的核心。定位器代表了一種在任何時刻在頁面上找到元素的方法,並用於對元素執行操作,如 .click
.fill
等。可以使用 Page.locator() 方法建立自訂定位器。
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
Locator getStarted = page.locator("text=Get Started");
assertThat(getStarted).hasAttribute("href", "/docs/intro");
getStarted.click();
Playwright 支援許多不同的定位器,如 role text, test id 等等。了解更多關於可用定位器以及如何選擇定位器的資訊,請參閱這個深入指南。
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
assertThat(page.locator("text=Installation")).isVisible();
測試隔離
Playwright 有一個 BrowserContext 的概念,它是一個在記憶體中隔離的瀏覽器配置檔。建議為每個測試建立一個新的 BrowserContext 以確保它們不會互相干擾。
Browser browser = playwright.chromium().launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();