网页应用测试 webapp-testing

这个技能是用于使用Playwright工具进行本地网页应用的自动化测试,支持验证前端功能、调试UI行为、捕获浏览器截图和查看浏览器日志。关键词:网页应用测试、Playwright、前端测试、UI调试、浏览器自动化、软件测试。

测试 0 次安装 0 次浏览 更新于 3/8/2026

name: webapp-testing description: 使用Playwright与本地网页应用交互和测试的工具包。支持验证前端功能、调试UI行为、捕获浏览器截图和查看浏览器日志。 source: anthropics/skills license: Apache-2.0

使用Playwright进行网页应用测试

设置

npm init playwright@latest

基本测试结构

import { test, expect } from '@playwright/test';

test('首页有标题', async ({ page }) => {
  await page.goto('http://localhost:3000');
  await expect(page).toHaveTitle(/My App/);
});

test('可以导航到关于页面', async ({ page }) => {
  await page.goto('http://localhost:3000');
  await page.click('text=关于');
  await expect(page).toHaveURL(/.*about/);
});

常见操作

导航

await page.goto('http://localhost:3000');
await page.goBack();
await page.reload();

点击

await page.click('button');
await page.click('text=提交');
await page.click('#submit-btn');
await page.click('[data-testid="submit"]');

表单输入

await page.fill('input[name="email"]', 'test@example.com');
await page.fill('#password', 'secret123');
await page.selectOption('select#country', 'USA');
await page.check('input[type="checkbox"]');

等待

await page.waitForSelector('.loaded');
await page.waitForURL('**/dashboard');
await page.waitForResponse('**/api/data');
await page.waitForTimeout(1000); // 尽量避免使用

断言

await expect(page.locator('h1')).toHaveText('欢迎');
await expect(page.locator('.items')).toHaveCount(5);
await expect(page.locator('button')).toBeEnabled();
await expect(page.locator('.modal')).toBeVisible();
await expect(page.locator('input')).toHaveValue('test');

截图

// 全页
await page.screenshot({ path: 'screenshot.png', fullPage: true });

// 仅元素
await page.locator('.chart').screenshot({ path: 'chart.png' });

控制台日志

page.on('console', msg => console.log(msg.text()));
page.on('pageerror', err => console.error(err.message));

网络拦截

await page.route('**/api/data', route => {
  route.fulfill({
    status: 200,
    body: JSON.stringify({ items: [] })
  });
});

运行测试

# 运行所有测试
npx playwright test

# 运行特定文件
npx playwright test tests/login.spec.ts

# 在headed模式下运行
npx playwright test --headed

# 使用UI运行
npx playwright test --ui