Skip to content

端-到-端测试使用 Playwright

中等 约 55 分钟

你将构建什么

简单 web page 使用表单 and Playwright E2E 测试 suite 那个导航到 page, fills in 表单, 提交它, and 验证 result.

学习目标

  • 安装 and 配置 Playwright
  • 编写 E2E 测试那个导航 and interact 使用真实 page
  • Use locators 到查找元素
  • Assert on page 内容 and URL
  • 理解 E2E 测试 trade-offs

前置要求

  • 基础 HTML and JavaScript
  • 简单 web page 到测试 (or 创建 one)
  • 节点.js and npm 安装

步骤

  1. 1

    安装 Playwright

    运行 npm init playwright@latest and follow 设置 wizard.

    预期结果

    Playwright 是安装使用示例测试.

  2. 2

    创建测试 page

    创建简单 HTML page 使用登录表单.

    代码
    <!DOCTYPE html>
    <html>
    <body>
      <form id="loginForm">
        <input type="text" id="username" placeholder="Username">
        <input type="password" id="password" placeholder="Password">
        <button type="submit">Login</button>
      </form>
      <div id="message" style="display:none">Welcome!</div>
    </body>
    </html>

    预期结果

    HTML page 使用登录表单是 创建.

  3. 3

    编写 E2E 测试

    创建 Playwright 测试那个导航到 page, fills 表单, and 提交.

    代码
    const { test, expect } = require('@playwright/test');
    
    test('login form works', async ({ page }) => {
      await page.goto('http://localhost:8080');
      await page.fill('#username', 'admin');
      await page.fill('#password', 'password');
      await page.click('button[type="submit"]');
      await expect(page.locator('#message')).toBeVisible();
      await expect(page.locator('#message')).toHaveText('Welcome!');
    });

    预期结果

    E2E 测试运行 in 真实浏览器 and 通过.

  4. 4

    添加 assertions and 错误情况

    添加测试 for 无效登录那个检查 for 错误消息.

    代码
    test('invalid login shows error', async ({ page }) => {
      await page.goto('http://localhost:8080');
      await page.fill('#username', 'wrong');
      await page.click('button[type="submit"]');
      await expect(page.locator('#error')).toHaveText('Invalid credentials');
    });

    预期结果

    错误情况 E2E 测试通过.

  5. 5

    添加边界测试用例

    为测试套件添加边界值用例:空数组、零值、最大值、null/undefined。边界用例是最容易出错的地方,必须显式覆盖。

    代码
    describe("boundary cases", () => {
      it("handles empty array", () => {
        expect(func([])).toEqual([]);
      });
    
      it("handles zero", () => {
        expect(func(0)).toBe(0);
      });
    
      it("handles null", () => {
        expect(() => func(null)).toThrow();
      });
    
      it("handles max value", () => {
        expect(func(Number.MAX_SAFE_INTEGER)).toBeDefined();
      });
    });

    预期结果

    所有边界用例通过,无未捕获异常。

自己动手试试

你学到了什么

你学习到 编写 E2E 测试使用 Playwright 那个 drive 真实浏览器, interact 使用元素, and assert on page 状态. E2E 测试验证完整用户 journey 但是 slower and 更多 brittle than 单元测试, 所以 use 它们 sparingly for 关键 flows.

相关资源

相关课程

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题