编写测试
简介
Playwright测试很简单,它们
- 执行操作,以及
- 断言状态是否符合预期。
在执行操作之前无需等待任何内容:Playwright 在执行每个操作前会自动等待一系列可操作性检查通过。
在执行检查时也无需处理竞态条件 - Playwright断言的设计方式使其能够描述最终需要满足的预期条件。
就是这样!这些设计选择让Playwright用户完全不必再担心测试中出现不稳定的超时和竞争条件检查。
你将学习
第一个测试
看看以下示例了解如何编写测试。注意文件名遵循test_
前缀约定以及每个测试名称的格式。
import re
from playwright.sync_api import Page, expect
def test_has_title(page: Page):
page.goto("https://playwright.dev/")
# Expect a title "to contain" a substring.
expect(page).to_have_title(re.compile("Playwright"))
def test_get_started_link(page: Page):
page.goto("https://playwright.dev/")
# Click the get started link.
page.get_by_role("link", name="Get started").click()
# Expects page to have a heading with the name of Installation.
expect(page.get_by_role("heading", name="Installation")).to_be_visible()
操作
导航
大多数测试将从导航页面到URL开始。之后,测试将能够与页面元素进行交互。
page.goto("https://playwright.dev/")
Playwright 将等待页面达到加载状态后再继续执行。了解更多关于 page.goto() 的选项。
交互
执行操作首先需要定位元素。Playwright使用Locators API来实现这一点。定位器表示在任何时刻查找页面上元素的方法,了解更多关于可用的不同类型的定位器。Playwright会在执行操作前等待元素变为可操作状态,因此无需等待它变为可用状态。
# Create a locator.
get_started = page.get_by_role("link", name="Get started")
# Click it.
get_started.click()
在大多数情况下,它会写成一行:
page.get_by_role("link", name="Get started").click()
基本操作
这是最常用的Playwright操作列表。请注意还有更多功能,请务必查看Locator API部分以了解更多信息。
操作 | 描述 |
---|---|
locator.check() | 勾选输入复选框 |
locator.click() | 点击元素 |
locator.uncheck() | 取消勾选输入复选框 |
locator.hover() | 鼠标悬停在元素上 |
locator.fill() | 填写表单字段,输入文本 |
locator.focus() | 聚焦元素 |
locator.press() | 按下单个按键 |
locator.set_input_files() | 选择要上传的文件 |
locator.select_option() | 在下拉菜单中选择选项 |
断言
Playwright 包含断言功能,这些断言会持续等待直到满足预期条件。使用这些断言可以让测试更加稳定可靠。例如,以下代码会一直等待直到页面标题包含"Playwright":
import re
from playwright.sync_api import expect
expect(page).to_have_title(re.compile("Playwright"))
以下是使用最广泛的异步断言列表。请注意还有更多可供了解:
测试隔离
Playwright Pytest插件基于测试夹具的概念,例如内置的page夹具,它会传递到您的测试中。由于Browser Context的隔离机制,页面在测试之间是隔离的,这相当于一个全新的浏览器配置文件,每个测试都会获得一个全新的环境,即使多个测试在单个浏览器中运行也是如此。
from playwright.sync_api import Page
def test_example_test(page: Page):
pass
# "page" belongs to an isolated BrowserContext, created for this specific test.
def test_another_test(page: Page):
pass
# "page" in this second test is completely isolated from the first test.
使用fixtures
您可以使用各种fixtures在测试前后执行代码,并在测试之间共享对象。一个function
作用域的fixture(例如使用autouse)的行为类似于beforeEach/afterEach。而一个module
作用域的fixture(使用autouse)则类似于beforeAll/afterAll,它会在所有测试之前和之后运行。
import pytest
from playwright.sync_api import Page, expect
@pytest.fixture(scope="function", autouse=True)
def before_each_after_each(page: Page):
print("before the test runs")
# Go to the starting url before each test.
page.goto("https://playwright.dev/")
yield
print("after the test runs")
def test_main_navigation(page: Page):
# Assertions use the expect API.
expect(page).to_have_url("https://playwright.dev/")