今天我们来看下微软自动化框架Playwright官方文档中的代码展示:
Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met. Playwright comes with auto-wait built in meaning it waits for elements to be actionable prior to performing actions. Playwright provides assertThat overloads to write assertions.
Take a look at the example test below to see how to write a test using web first assertions, locators and selectors.
官方文档中举了个例子,用到了创建Playwright, 再创建一个浏览器,定义页面,新打开一个页面,找到元素。和之前我写的Demo差不多,但是官方的代码更规范。接下来我们看看对应的代码:
package org.example;import com.microsoft.playwright.*;import com.microsoft.playwright.options.AriaRole;import java.util.regex.Pattern;import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;public class NewPlaywrightDemo {
public static void main(String[] args){
//创建Playwright try(Playwright playwright = Playwright.create()) {
//新建浏览器 Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(false)); //创建新页面 Page page = browser.newPage(); //导航到要测试验证的页面 page.navigate("http://playwright.dev"); Thread.sleep(30000); //期望标题包含一个 子字符串 assertThat(page).hasTitle(Pattern.compile("Playwright")); //创建一个锚点 Locator getStarted = page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions()
.setName("Get Started")); //期望等待一个属性 assertThat(getStarted).hasAttribute("href","/docs/intro"); //点击要开始的链接 getStarted.click(); // assertThat(page).hasURL(Pattern.compile(".*intro")); } catch (Exception e){
e.printStackTrace(); }
}
}
接下来介绍的是 判断
Playwright provides assertThat
overloads which will wait until the expected condition is met.
assertThat(page).hasTitle(Pattern.compile("Playwright"));
定位 Locators
Locator getStarted = page.locator("text=Get Started");
assertThat(getStarted).hasAttribute("href", "/docs/intro");
getStarted.click();
Playwright supports many different locators like role text, test id
and many more. Learn more about available locators
and how to pick one in this in-depth guide.
assertThat(page.locator("text=Installation")).isVisible();
今天先到这里,明天继续