Token导航 LogoToken导航TokenDH.com
前端设计操作浏览器github未标认证来源可访问许可证需确认审计通过

playwright-e2e-testingPlaywright E2E 测试

Agent Skill

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

总安装

2,376

周安装

98

GitHub Stars

124

下载量

776
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:playwright-e2e-testing(Playwright E2E 测试)
来源仓库:https://github.com/fugazi/test-automation-skills-agents
仓库路径:skills/playwright-e2e-testing
安装命令:
npx skills add https://github.com/fugazi/test-automation-skills-agents --skill playwright-e2e-testing
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/fugazi/test-automation-skills-agents --skill playwright-e2e-testing

简介

playwright-e2e-testing 用于辅助测试设计、自动化测试、用例整理和回归验证,适合让 Agent 编写端到端测试或生成测试计划。

  • 适用于需要端到端测试覆盖的场景,如 Web 应用功能验证。
  • 使用时需确认项目测试框架和运行命令,避免为了通过测试而破坏真实逻辑。
  • 涉及浏览器或外部服务时,应明确区分本地模拟与生产环境。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Playwright E2E Testing (TypeScript)

Comprehensive toolkit for end-to-end testing of web applications using Playwright with TypeScript. Enables robust UI testing, API validation, and responsive design verification following best practices.

Activation: This skill is triggered when working with Playwright tests, browser automation, E2E testing, API testing with Playwright, or test infrastructure setup.

When to Use This Skill

  • Write E2E tests for user flows, forms, navigation, and authentication
  • API testing via request fixture or network interception during UI tests
  • Responsive testing across mobile, tablet, and desktop viewports
  • Debug flaky tests using traces, screenshots, videos, and Playwright Inspector
  • Setup test infrastructure with Page Object Model and fixtures
  • Mock/intercept APIs for isolated, deterministic testing
  • Visual regression testing with screenshot comparisons

Prerequisites

RequirementDetails
Node.jsv18+ recommended
Package Managernpm, yarn, or pnpm
Playwright@playwright/test package
TypeScripttypescript + ts-node (optional but recommended)
BrowsersInstalled via npx playwright install

Quick Setup

# Initialize new project
npm init playwright@latest

# Or add to existing project
npm install -D @playwright/test
npx playwright install

First Questions to Ask

Before writing tests, clarify:

  1. App URL: Local dev server command + port, or staging URL?
  2. Critical flows: Which user journeys must be covered (happy path + error states)?
  3. Browsers/devices: Chrome, Firefox, Safari? Mobile viewports?
  4. API strategy: Real backend, mocked responses, or hybrid?
  5. Test data: Seed data available? Reset/cleanup strategy?

Core Principles

1. Test Runner & TypeScript

Always use @playwright/test with TypeScript for type safety and better IDE support.

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

test("user can login", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("user@test.com");
  await page.getByLabel("Password").fill("password123");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(/.*dashboard/);
});

2. Locator Strategy (Priority Order)

PriorityLocatorExample
1Role + accessible namegetByRole('button', {name: 'Submit'})
2LabelgetByLabel('Email')
3PlaceholdergetByPlaceholder('Enter email')
4TextgetByText('Welcome')
5Test IDgetByTestId('submit-btn')
6CSS (avoid)locator('.btn-primary')

See Locator Strategies Guide for detailed patterns.

3. Auto-Waiting & Web-First Assertions

Playwright auto-waits for elements. Never use sleep() or arbitrary timeouts.

// ✅ Web-first assertions (auto-retry)
await expect(page.getByRole("alert")).toBeVisible();
await expect(page).toHaveURL(/dashboard/);
await expect(page.getByTestId("status")).toHaveText("Success!");

// ❌ Avoid manual waits
await page.waitForTimeout(2000); // Bad practice

4. Test Structure with Steps

Use test.step() for readable reports and failure localization:

test("checkout flow", async ({ page }) => {
  await test.step("Add item to cart", async () => {
    await page.goto("/products/1");
    await page.getByRole("button", { name: "Add to Cart" }).click();
  });

  await test.step("Complete checkout", async () => {
    await page.goto("/checkout");
    await page.getByRole("button", { name: "Pay Now" }).click();
  });

  await test.step("Verify confirmation", async () => {
    await expect(page.getByRole("heading")).toContainText("Order Confirmed");
  });
});

Key Workflows

Forms & Navigation

// Form submit and wait for navigation (auto-waiting)
await page.getByRole("button", { name: "Login" }).click();
await expect(page).toHaveURL(/.*dashboard/);

// Form with API response validation
const responsePromise = page.waitForResponse(
  (r) => r.url().includes("/api/login") && r.status() === 200,
);
await page.getByRole("button", { name: "Login" }).click();
const response = await responsePromise;

API Testing (Request Fixture)

test("API health check", async ({ request }) => {
  const response = await request.get("/api/health");
  expect(response.ok()).toBeTruthy();
  expect(await response.json()).toMatchObject({ status: "ok" });
});

API Mocking & Interception

test("handles API error", async ({ page }) => {
  await page.route("**/api/users", (route) =>
    route.fulfill({
      status: 500,
      body: JSON.stringify({ error: "Server error" }),
    }),
  );
  await page.goto("/users");
  await expect(page.getByRole("alert")).toContainText("Something went wrong");
});

Responsive Testing

const viewports = [
  { width: 375, height: 667, name: "mobile" },
  { width: 768, height: 1024, name: "tablet" },
  { width: 1280, height: 720, name: "desktop" },
];

for (const vp of viewports) {
  test(`navigation works on ${vp.name}`, async ({ page }) => {
    await page.setViewportSize(vp);
    await page.goto("/");
    // Mobile: hamburger menu
    if (vp.width < 768) {
      await page.getByRole("button", { name: /menu/i }).click();
    }
    await page.getByRole("link", { name: "About" }).click();
    await expect(page).toHaveURL(/about/);
  });
}

Configuration

Use playwright.config.ts for project-wide settings:

import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  retries: process.env.CI ? 2 : 0,
  reporter: [["html"], ["junit", { outputFile: "results.xml" }]],
  use: {
    baseURL: "http://localhost:3000",
    trace: "on-first-retry",
    screenshot: "only-on-failure",
    video: "retain-on-failure",
  },
  projects: [
    { name: "chromium", use: devices["Desktop Chrome"] },
    { name: "mobile", use: devices["Pixel 5"] },
  ],
  webServer: {
    command: "npm run dev",
    url: "http://localhost:3000",
    reuseExistingServer: !process.env.CI,
  },
});

Troubleshooting

ProblemCauseSolution
Element not foundWrong locator or not renderedUse PWDEBUG=1 to inspect, verify with getByRole
Timeout waitingElement hidden or slow loadCheck for overlays, increase timeout, use waitFor()
Flaky testsRace conditions, animationsAdd test.step(), use proper waits, disable animations
Strict mode violationMultiple elements matchUse .first(), .filter(), or more specific locator
Screenshots differDynamic contentMask dynamic areas, use deterministic data
CI fails, local passesEnvironment differencesCheck baseURL, timeouts, webServer config
API mock not workingRoute pattern mismatchUse **/api/... glob, verify with page.on('request')

CLI Quick Reference

CommandDescription
npx playwright testRun all tests headless
npx playwright test --uiOpen UI mode (interactive)
npx playwright test --headedRun with visible browser
npx playwright test --debugRun with Playwright Inspector
npx playwright test -g "login"Run tests matching pattern
npx playwright test --project=chromiumRun specific project
npx playwright show-reportOpen HTML report
npx playwright codegenGenerate tests by recording
PWDEBUG=1 npx playwright testDebug with Inspector
DEBUG=pw:api npx playwright testVerbose API logging

Common Rationalizations

Common shortcuts and "good enough" excuses that erode test quality — and the reality behind each.
RationalizationReality
"I'll add assertions later"A test without assertions is a script, not a test. Add meaningful assertions now — later never comes.
"This selector is stable enough"CSS selectors break on refactor. Use data-testid or role-based locators for stability.
"The test passes on my machine"Local passes don't guarantee CI passes. Always validate in the target environment.
"Skip the edge cases for now"Edge cases are where production bugs live. Test them first, not last.
"Visual tests aren't needed"Visual regression catches CSS/layout bugs that functional assertions miss entirely.
"This API won't change"APIs evolve constantly. Contract tests prevent silent downstream failures.
"One browser is enough"Cross-browser issues are real and common. Test at least Chromium and Firefox.
"networkidle is fine for waiting"networkidle is deprecated and unreliable. Wait for specific conditions (elements, responses, URL changes).

References

DocumentContent
SnippetsReady-to-use code patterns
Locator StrategiesComplete locator guide
Page Object ModelPOM implementation patterns
Debugging GuideTroubleshooting & debugging techniques

Verification

After completing this skill's workflow, confirm:

  • Test file follows naming convention — File named *.spec.ts in the appropriate directory
  • Uses custom fixture injection — No new PageObject() calls in spec files; all POMs injected via fixtures
  • Locators use recommended strategies — All locators use getByRole(), getByTestId(), or getByText(); no CSS selectors for interactive elements
  • Auto-waiting patterns used — No page.waitForTimeout() or sleep() calls; all waits use waitForSelector(), waitForURL(), or built-in auto-waiting
  • Tests are independent — Each test sets up and tears down its own state; no beforeAll with shared mutable state
  • Error states covered — At least one test verifies error/empty/loading states alongside happy path
  • All tests passnpx playwright test exits with code 0
  • No skipped testsgrep -R -E "test\.skip|test\.fixme" --include="*.spec.ts". returns no results

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude

34.46%
按下载量换算267

Codex

34.25%
按下载量换算266

Cursor

18.62%
按下载量换算144

Gemini CLI

8.89%
按下载量换算69

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills