蓝色天空网mbsky.com · 知识 · 实践 · 创造Playwright · 本地阅读预览
教程 / AI / 智能开发 / Playwright

Playwright Test

系统核对 Playwright Test 测试运行器、playwright.config.ts 多项目配置、自定义 Fixture 与页面对象、storageState 前置登录复用、步骤附件及 CLI 报告体系,并结合离线 Chromium 实测核心自动化行为。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

测试框架概述与核心配置

Playwright Test 是 Playwright 官方内置的端到端测试框架,自带测试运行器与 `expect` Web 优先断言库,无需额外引入 Jest 或 Mocha。它在每次执行 `test()` 时自动分配独立的 Browser Context 保证隔离,并原生集成按文件并行执行、失败重试、截图录屏、Trace 追踪与 HTML 报告等工程能力。

在 Node.js 项目中可通过 `npm init playwright@latest` 初始化脚手架并生成 `playwright.config.js`(或 `.ts`)。该入口使用 `defineConfig({...})` 集中管理 `testDir`、单测 `timeout`、`retries`、并行 `workers`、`reporter`(如 `[['html'], ['list']]`),以及 `use` 下的 `headless`、`baseURL`、`screenshot`、`video`、`trace`、`viewport`、`locale` 与多浏览器 `projects`。

标准测试脚本由三部分构成:从 `@playwright/test` 导入 `test` 与 `expect`;用 `test(name, async ({ page }) => ...)` 编写用例并通过 `page.goto()` 与 `expect(page).toHaveTitle()` 完成校验;再借助 `test.describe()` 进行逻辑分组,配合 `beforeEach`/`afterEach` 统一前后置处理。

编写测试用例、运行控制与重试机制

实际编写套件时,单个 `test()` 负责验证独立场景(如标题正则校验),`test.describe()` 将登录或购物车等同类场景聚合成模块,`beforeEach`/`afterEach` 负责页面导航与截图收尾;面对多组账号(如 `admin` 与 `guest`),可直接用 `for...of` 循环生成参数化用例。本站离线 Chromium(158.0.8127.38)实测参数化登录循环:两组账号各自获得初始 `0` 条 Cookie 的全新隔离上下文,并分别断言 `.welcome` 显示 `Welcome admin` 与 `Welcome guest`。

执行与报告层面,可通过 `npx playwright test` 运行全量测试、指定单个 `*.spec.js` 文件或用 `-g "关键词"` 过滤用例;框架默认按文件并行执行,可用 `--workers=4` 调整并发数;执行完毕后运行 `npx playwright show-report` 打开交互式 HTML 报告。对于偶发网络或渲染抖动,在配置中开启 `retries: 2` 即可自动重试。本站离线实测模拟首请求返回 HTTP 503、次请求返回 200 的不稳定接口,在 `retries=2` 策略下第 `2` 次尝试即稳定恢复并匹配标题 `Recovered OK`。

完整测试套件架构:多项目、夹具与页面对象

规范的端到端工程常划分为 `playwright.config.ts`、`tests/auth.setup.ts`、`tests/smoke/home.spec.ts`、`tests/e2e/cart.spec.ts`、`fixtures/pages.ts`、`fixtures/test.extend.ts` 与视觉基线目录 `snapshots/`。`projects` 让同一套用例在桌面 Chromium、Firefox、移动 Pixel 7 等配置下复用,而 `use` 遵循“全局 < 项目 < 单测”三级覆盖;本站实测全局 `1366×900 / zh-CN`、项目覆盖为 `393×851`、单测再覆盖为 `en-US` 时,浏览器内实测视口与 `navigator.language` 精确解析为 `[393, 851]` 与 `en-US`。

为了避免重复书写选择器,可将页面元素与业务动作封装为页面对象(如 `HomePage` 与 `CartPage`),再通过 `base.extend<MyFixtures>()` 注册为自定义 `home` 与 `cart` 夹具(Fixture),测试用例只需在参数解构中声明即可自动注入并共享同一 `page` 实例。

涉及登录态的套件推荐设置独立的 `setup` 项目(`testMatch: /auth\.setup\.ts/`),执行一次登录后调用 `page.context().storageState({ path: 'storageState.json' })` 持久化 Cookie 与 `localStorage`,业务项目通过 `dependencies: ['setup']` 与 `use: { storageState: 'storageState.json' }` 直接免登录启动。本站离线实测导出 `storageState.json` 并在新上下文加载后,访问 `/cart` 无需重新登录即可直接读回 `auth_user=tester` 与 `tok_tester`。冒烟用例则可组合 `toHaveTitle`、`toHaveURL` 与官方推荐的 `expect(page).toHaveScreenshot()` 视觉回归(优先于手写 `page.screenshot()` 配 `toMatchSnapshot()`)。

复杂 E2E 用例建议用 `test.describe.configure({ mode: 'parallel' })` 开启组内并行,用 `test.step()` 分层记录操作步骤,并借助 `test.info().attach()` 附加 JSON 状态或元素截图以便在报告中溯源。本站离线实测完整 `HomePage`/`CartPage` 流程:前置进入首页、点击 `Add Item #1` 后 `[data-test=cart-count]` 精准变为 `1`,元素截图与全页截图均生成有效 PNG(`\x89PNG` 文件头),调试 JSON 载荷完整记录。CLI 还可按目录、`-g`、`--project`、`--update-snapshots` 或 `--debug`(Inspector)精细调度。

Playwright Test 常用 API 速查

下表按测试与分组、夹具与配置、断言(`expect`)、步骤与附件、报告与 CLI 五个维度整理 Playwright Test 高频接口。所有运行参数、Fixture 作用域、视觉快照与 Reporter 扩展细节均应以官方文档为准,附件亦可在步骤级(`TestStepInfo`)附加。

测试定义、分组与生命周期 API

API作用
test(name, fn)定义单个独立测试用例,自动注入隔离的 page/context 夹具
test.describe(title, fn)按业务模块对相关用例进行逻辑分组
test.describe.configure({ mode })控制当前分组执行模式(parallel 并行或 serial 串行)
test.beforeAll / test.afterAll在分组或文件级所有用例前后各执行一次初始化与清理
test.beforeEach / test.afterEach在每条用例执行前后分别运行前置准备与后置收尾
test.skip / only / fixme / slow / fail控制用例跳过、独占调试、待修复标记、3 倍超时或预期失败

夹具扩展与配置入口 API

API作用
test.extend<Fixtures>(defs)扩展自定义夹具(如封装好的页面对象实例)并在用例中按名注入
test.use(options)在文件或分组级别覆盖 storageState、viewport、locale 等运行选项
defineConfig({...})带类型提示的配置入口,集中设置 testDir、timeout、retries、workers、reporter 等
projects声明多浏览器、移动设备或 setup 依赖项目矩阵
use: { baseURL, trace, video, screenshot, viewport, locale, timezoneId, storageState }统一配置浏览器上下文环境与失败取证采集策略

内置断言(expect)常用类别

API作用
expect(value).toBe / toEqual / toContain ...同步通用值断言,不执行轮询等待
expect(locator).toHaveText / Value / AttributeWeb 优先内容与属性断言,内置自动重试直至超时
expect(locator).toBeVisible / Hidden / Enabled / Disabled / Checked元素可见性与交互状态断言(带自动重试)
expect(page).toHaveTitle / URL校验页面标题与当前 URL(支持字符串或正则)
expect(page/locator).toHaveScreenshot([name, options])页面或元素级视觉快照回归对比(自动管理基线)

步骤分层与报告附件 API

API作用
test.step(name, fn)将长流程拆分为带标题的层级步骤,在报告中折叠展示
test.info().attach(name, { path, body, contentType })将截图、JSON 状态或日志文件附加到当前测试或步骤报告中

报告配置与常用 CLI 命令

命令/配置作用
reporter: [['html', { outputFolder }], ['list']]同时启用 HTML 归档报告与终端列表输出
npx playwright test --project="Chromium"仅运行配置中指定的单个项目(如 Chromium)
-g "keyword" / --grep / --grep-invert按标题或标签正向筛选或反向排除测试用例
--update-snapshots重新生成并覆盖视觉回归基线快照
npx playwright show-report启动本地静态服务并在浏览器中查看最新 HTML 报告

离线 Chromium 实测页面对象、storageState 复用、步骤截图与重试配置

python · 阅读源码
"""Offline Playwright Chromium lab for Chapter 11: Playwright Test."""
import json
import os
import re
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from playwright.sync_api import sync_playwright, expect


FLAKY_HITS = {"count": 0}


class DemoHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        return

    def _send(self, code, body, content_type="text/html; charset=utf-8", extra_headers=None):
        data = body.encode("utf-8") if isinstance(body, str) else body
        self.send_response(code)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(data)))
        if extra_headers:
            for k, v in extra_headers.items():
                self.send_header(k, v)
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/":
            self._send(
                200,
                "<!doctype html><html><head><title>Playwright Test Demo Home</title></head>"
                "<body><h1>Home</h1><a href='/e2e'>ToDo MVC &amp; E2E Cart</a></body></html>",
            )
        elif self.path == "/login":
            self._send(
                200,
                "<!doctype html><html><head><title>Login</title></head><body>"
                "<input id='username'><input id='password' type='password'>"
                "<button id='submit' onclick=\""
                "const u=document.getElementById('username').value;"
                "document.cookie='auth_user='+u+'; path=/';"
                "localStorage.setItem('auth_token','tok_'+u);"
                "document.getElementById('msg').textContent='Welcome '+u;"
                "document.getElementById('msg').style.display='block';"
                "\">登录</button>"
                "<div id='msg' class='welcome' style='display:none'></div>"
                "</body></html>",
            )
        elif self.path == "/cart":
            cookie = self.headers.get("Cookie", "")
            self._send(
                200,
                "<!doctype html><html><head><title>Cart</title></head><body>"
                f"<div id='cookie-echo'>{cookie}</div>"
                "<div id='token-echo'></div>"
                "<script>document.getElementById('token-echo').textContent=localStorage.getItem('auth_token')||'none';</script>"
                "</body></html>",
            )
        elif self.path == "/e2e":
            self._send(
                200,
                "<!doctype html><html><head><title>E2E Cart</title></head><body>"
                "<button id='add-item' onclick=\""
                "const el=document.querySelector('[data-test=cart-count]');"
                "el.textContent=String(Number(el.textContent)+1);"
                "\">Add Item #1</button>"
                "<span id='cart-count' data-test='cart-count'>0</span>"
                "</body></html>",
            )
        elif self.path == "/flaky":
            FLAKY_HITS["count"] += 1
            if FLAKY_HITS["count"] == 1:
                self._send(503, "<!doctype html><html><head><title>Temporary Error</title></head><body>503</body></html>")
            else:
                self._send(200, "<!doctype html><html><head><title>Recovered OK</title></head><body><p id='ok'>ready</p></body></html>")
        else:
            self._send(404, "not found")


class HomePage:
    def __init__(self, page, base_url):
        self.page = page
        self.base_url = base_url

    def goto(self):
        self.page.goto(f"{self.base_url}/")

    @property
    def todo_link(self):
        return self.page.get_by_role("link", name=re.compile("ToDo MVC", re.I))


class CartPage:
    def __init__(self, page, base_url):
        self.page = page
        self.base_url = base_url

    def goto(self):
        self.page.goto(f"{self.base_url}/e2e")

    @property
    def add_first_item(self):
        return self.page.get_by_role("button", name=re.compile(r"Add .* #1", re.I))

    @property
    def cart_count(self):
        return self.page.locator("[data-test=cart-count]")

    def add_one(self):
        self.add_first_item.click()

    def expect_count(self, n):
        expect(self.cart_count).to_have_text(str(n))


def launch_browser(p):
    for kwargs in (dict(channel="chrome", headless=True), dict(channel="msedge", headless=True), dict(headless=True)):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No local Chromium executable found")


def main():
    server = ThreadingHTTPServer(("127.0.0.1", 0), DemoHandler)
    port = server.server_address[1]
    base_url = f"http://127.0.0.1:{port}"
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with tempfile.TemporaryDirectory() as tmpdir, sync_playwright() as p:
            tmp = Path(tmpdir)
            browser = launch_browser(p)

            # Case 1: Parameterized data-driven tests with isolated contexts + HomePage PO
            users = [("admin", "123456"), ("guest", "guest")]
            welcomes = []
            cookie_counts_before = []
            for name, pwd in users:
                ctx = browser.new_context()
                page = ctx.new_page()
                home = HomePage(page, base_url)
                home.goto()
                expect(page).to_have_title(re.compile("Playwright Test Demo"))
                expect(home.todo_link).to_be_visible()
                cookie_counts_before.append(len(ctx.cookies()))
                page.goto(f"{base_url}/login")
                page.fill("#username", name)
                page.fill("#password", pwd)
                page.click("#submit")
                expect(page.locator(".welcome")).to_be_visible()
                welcomes.append(page.locator(".welcome").text_content())
                ctx.close()
            actual1 = {"welcomes": welcomes, "isolated_initial_cookies": cookie_counts_before}
            expected1 = {"welcomes": ["Welcome admin", "Welcome guest"], "isolated_initial_cookies": [0, 0]}
            cases.append(dict(name="pom_and_data_driven_login", expected=expected1, actual=actual1, passed=actual1 == expected1))

            # Case 2: auth.setup generating storageState.json and reusing in logged-in project
            state_path = tmp / "storageState.json"
            setup_ctx = browser.new_context()
            setup_page = setup_ctx.new_page()
            setup_page.goto(f"{base_url}/login")
            setup_page.fill("#username", "tester")
            setup_page.fill("#password", "pw123")
            setup_page.click("#submit")
            expect(setup_page).to_have_url(re.compile(r"/login$"))
            setup_ctx.storage_state(path=str(state_path))
            setup_ctx.close()

            reused_ctx = browser.new_context(storage_state=str(state_path))
            reused_page = reused_ctx.new_page()
            reused_page.goto(f"{base_url}/cart")
            actual2 = {
                "state_file_exists": state_path.exists(),
                "cookie_echo": reused_page.locator("#cookie-echo").text_content(),
                "token_echo": reused_page.locator("#token-echo").text_content(),
            }
            expected2 = {
                "state_file_exists": True,
                "cookie_echo": "auth_user=tester",
                "token_echo": "tok_tester",
            }
            reused_ctx.close()
            cases.append(dict(name="storage_state_setup_and_reuse", expected=expected2, actual=actual2, passed=actual2 == expected2))

            # Case 3: E2E Cart with beforeEach/afterEach hooks, steps, attachment & element screenshot
            steps_log = []
            ctx3 = browser.new_context(viewport={"width": 1366, "height": 900}, locale="zh-CN")
            page3 = ctx3.new_page()
            home3 = HomePage(page3, base_url)
            cart3 = CartPage(page3, base_url)
            # beforeEach
            steps_log.append("beforeEach:home")
            home3.goto()
            # test steps
            steps_log.append("step:add_item")
            cart3.goto()
            cart3.add_one()
            cart3.expect_count(1)
            badge_png = cart3.cart_count.screenshot()
            full_png = page3.screenshot(path=str(tmp / "cart.png"))
            attach_json = json.dumps({"note": "after add", "count": 1})
            # afterEach
            steps_log.append("afterEach:screenshot")
            actual3 = {
                "steps": steps_log,
                "count_text": cart3.cart_count.text_content(),
                "badge_png_valid": badge_png.startswith(b"\x89PNG"),
                "full_png_valid": full_png.startswith(b"\x89PNG") and (tmp / "cart.png").exists(),
                "attachment_count": json.loads(attach_json)["count"],
            }
            expected3 = {
                "steps": ["beforeEach:home", "step:add_item", "afterEach:screenshot"],
                "count_text": "1",
                "badge_png_valid": True,
                "full_png_valid": True,
                "attachment_count": 1,
            }
            ctx3.close()
            cases.append(dict(name="cart_e2e_steps_hooks_and_attachments", expected=expected3, actual=actual3, passed=actual3 == expected3))

            # Case 4: Retry mechanism (retries=2) + global/project/test use-option override layering
            FLAKY_HITS["count"] = 0
            attempts = 0
            recovered_title = None
            for attempt in range(3):  # 1 initial + retries=2
                attempts += 1
                ctx_r = browser.new_context()
                pg_r = ctx_r.new_page()
                resp = pg_r.goto(f"{base_url}/flaky")
                if resp.status == 200:
                    expect(pg_r.locator("#ok")).to_have_text("ready")
                    recovered_title = pg_r.title()
                    ctx_r.close()
                    break
                ctx_r.close()

            global_use = {"viewport": {"width": 1366, "height": 900}, "locale": "zh-CN"}
            project_use = {**global_use, "viewport": {"width": 393, "height": 851}}
            test_use = {**project_use, "locale": "en-US"}
            ctx_cfg = browser.new_context(**test_use)
            pg_cfg = ctx_cfg.new_page()
            pg_cfg.set_content("<p>cfg</p>")
            measured_vp = pg_cfg.evaluate("() => ({w: window.innerWidth, h: window.innerHeight, lang: navigator.language})")
            ctx_cfg.close()

            actual4 = {
                "attempts_needed": attempts,
                "recovered_title": recovered_title,
                "resolved_viewport": [measured_vp["w"], measured_vp["h"]],
                "resolved_locale": measured_vp["lang"],
            }
            expected4 = {
                "attempts_needed": 2,
                "recovered_title": "Recovered OK",
                "resolved_viewport": [393, 851],
                "resolved_locale": "en-US",
            }
            cases.append(dict(name="retry_and_suite_config_contract", expected=expected4, actual=actual4, passed=actual4 == expected4))

            browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对参数化登录隔离上下文(初始 Cookie 均为 0)、storageState 导出与免登录复用、购物车计数断言与 PNG 截图生成,以及 503 重试第 2 次成功与三级 use 配置覆盖结果。
离线 Chromium 实测页面对象、storageState 复用、步骤截图与重试配置

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:34503fe1f633367de0e9ea376caf103ac3d053f96ed23c5baca68b141eece490

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Playwright Test实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:dafd2d867e0778807b5727840e400f9953891ff0d532316b8f0bf90fe4e6eeac

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 Playwright Test 中,为什么要通过独立的 setup 项目生成 storageState.json,而不是在每条业务用例里重复执行登录表单?

展开参考解答

将登录抽离到 setup 项目仅需执行一次即可导出 Cookie 与 localStorage 快照,其余业务项目声明 dependencies 与 storageState 后可复用登录态并保持上下文隔离,显著缩短套件耗时且避免登录接口成为并发瓶颈。

规范与官方依据