Token导航 LogoToken导航

Agent Skill · 开发

playwright-e2e-testing(Playwright E2E 测试)

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

playwright-e2e-testing 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为操作浏览器;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 18,928。

总安装 306周安装 13GitHub Stars 公开资料未说明下载 107核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/perdolique/workflow --skill playwright-e2e-testing

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于辅助测试设计、自动化测试和回归验证。playwright-e2e-testing 属于开发类 Skill,可作为该场景下的辅助能力补充。适合编写单元测试、端到端测试或根据失败日志定位问题。使用时需确认项目测试框架、运行命令和夹具数据,避免误改逻辑。涉及浏览器或外部服务时应区分本地模拟、测试和生产环境。

归类为开发类,符合其测试支持的功能定位。

来源仓库内路径:skills/playwright-e2e-testing

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/perdolique/workflow --skill playwright-e2e-tes…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要操作浏览器,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

playwright-e2e-testing 怎么安装?

在终端执行 npx skills add https://github.com/perdolique/workflow --skill playwright-e2e-testing。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

playwright-e2e-testing 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

playwright-e2e-testing 需要什么权限?

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

playwright-e2e-testing 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

playwright-e2e-testing 用的人多吗?

公开数据是累计安装 306 次,近一周安装 13 次,下载 107 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

playwright-e2e-testing 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
playwright-e2e-testing

Playwright E2E 测试 · 本页

306—操作浏览器未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

E2E testing with Playwright

This skill provides patterns and conventions for writing Playwright E2E tests for web applications, including SPA-specific techniques for routing, API mocking, and async navigation.

When to use this skill

  • Writing E2E/browser tests for user flows
  • Testing page routing and redirects
  • Testing dialog/modal interactions
  • Creating test data fixtures for a new feature
  • Mocking API endpoints for E2E tests
  • Debugging failing Playwright tests

Project configuration

When setting up or modifying playwright.config.ts, see references/configuration.md for conventions on web server setup, reporters, traces, screenshots, and CI behavior.

Test imports

If the project has a custom fixture file that extends Playwright's test object (common for API interception, shared setup, etc.), always import test and expect from that fixture — not from @playwright/test directly. Check the project's test directory for a fixtures/ folder or global.fixtures.ts.

// ✅ If project has custom fixtures — import from there
import { test, expect } from '../fixtures/global.fixtures.ts';

// ❌ Bypasses any project-level request interception or setup
import { test, expect } from '@playwright/test';

Standalone types are always fine to import directly:

import type { Page, Locator } from '@playwright/test';

Directory structure

Organize tests by feature domain. Each domain typically has its own fixture file:

tests/playwright/
├── constants.ts                     # Base URLs, shared constants
├── fixtures/
│   ├── global.fixtures.ts           # Extended test/expect (if project uses one)
│   ├── core-api.fixtures.ts         # Shared API mock helpers
│   └── {feature}.fixtures.ts        # Feature-specific test data
├── {feature-domain}/
│   └── {feature}.test.ts            # Test file
└── routing/
    └── redirects.test.ts            # Router/redirect tests

Writing test files

Basic structure

import type { Page } from '@playwright/test';
import { test, expect } from '../fixtures/global.fixtures.ts';
import { mockEndpoint } from '../fixtures/api.fixtures.ts';
import { baseFixture, variantFixture } from '../fixtures/{feature}.fixtures.ts';

// Helper functions (navigation, assertions)
async function openFeaturePage(page: Page): Promise<void> {
  await page.goto('/feature?id=test-id');
}

test.describe('Feature name', () => {
  test('description of expected behavior', async ({ page }) => {
    await mockEndpoint(page, baseFixture);
    await openFeaturePage(page);
    await expect(page.getByText('Expected text')).toBeVisible();
  });
});

Helper functions

Define helper functions at the top of the test file for repeated actions. Helpers improve readability and reduce duplication:

  • Navigation helpers — openDialog(page), gotoProductPage(page)
  • Assertion helpers — expectSummary(page, options), expectAvailability(page, from, to)
  • Setup helpers — setupCommonMocks(page) for test-specific mock bundles
  • Locator helpers — actionButtons(page) returning a Locator

Shared setup with beforeEach

When all tests in a describe block share identical mock setup:

test.describe('Router redirects', () => {
  test.beforeEach(async ({ page }) => {
    await setupCommonMocks(page);
  });

  test('redirects when resource is not found', async ({ page }) => {
    await page.goto('/resource?id=unknown');
    await expect(page).toHaveURL(/\/error\?id=unknown$/u);
  });
});

Multi-step flows with test.step()

For complex user flows (purchases, form submissions), use test.step() blocks. Playwright reports show which step failed, making debugging much faster.

test('completes purchase flow', async ({ page }) => {
  await test.step('prepare mocks', async () => {
    await mockProduct(page, productFixture);
    await mockCheckout(page);
  });

  const purchaseRequestPromise = page.waitForRequest(
    request => request.url().includes('/purchases') && request.method() === 'POST'
  );

  await test.step('open product page', async () => {
    await gotoProductPage(page);
  });

  await test.step('select option', async () => {
    await page.getByRole('button', { name: '14:00' }).click();
  });

  await test.step('verify confirmation page', async () => {
    await expect.poll(() => new URL(page.url()).pathname).toBe('/order-confirmation');
  });

  await test.step('submit order', async () => {
    await page.getByRole('button', { name: 'Confirm' }).click();
  });

  await test.step('verify purchase request', async () => {
    const request = await purchaseRequestPromise;

    expect(request.postDataJSON()).toEqual({
      items: [{ id: 'product-1', date: '2088-04-21T11:00:00.000Z' }]
    });
  });
});

Key patterns in multi-step flows:

  • page.waitForRequest() — Set up BEFORE the action that triggers the request
  • expect.poll() — Wait for async URL changes after SPA navigation
  • satisfies — Type-check request payload expectations without losing literal types

localStorage setup via addInitScript

To set localStorage values before the page loads (e.g., saved state for routing tests):

async function setSavedState(page: Page, key: string, value: unknown): Promise<void> {
  await page.addInitScript(
    ({ storageKey, data }: { storageKey: string; data: string }) => {
      localStorage.setItem(storageKey, data);
    },
    { storageKey: key, data: JSON.stringify(value) }
  );
}

addInitScript runs before the page loads, so the app reads the correct localStorage values during initialization. page.evaluate runs after the page loads, which is too late for route guards.

Selector patterns

Prefer user-facing selectors in this order:

  1. page.getByRole('button', {name: 'Confirm'}) — Accessible role + name
  2. page.getByText('Expected text') — Visible text content
  3. page.getByTestId('action-button') — data-testid attribute
  4. page.getByText('text', {exact: true}) — Exact match to avoid partial hits
  5. page.getByText(/regex pattern/u) — Regex for dynamic content

Use .first() when multiple identical elements exist on the page (e.g., text duplicated for mobile/desktop viewports).

Assertion patterns

// Visibility
await expect(page.getByText('Welcome')).toBeVisible();

// Element count
await expect(page.getByRole('button', { name: /\d{2}:\d{2}/u })).toHaveCount(3);
await expect(page.getByText('Not present')).toHaveCount(0); // Assert absence

// URL matching
await expect(page).toHaveURL('http://localhost:5050/error?id=unknown');
await expect(page).toHaveURL(/\/order-success\?id=test-id$/u);

// Async URL change (SPA navigation)
await expect.poll(() => new URL(page.url()).pathname).toBe('/order-confirmation');

// Interactive state
await expect(page.getByRole('button', { name: 'Submit' })).toBeEnabled();
await expect(page.getByRole('button', { name: 'Submit' })).toBeDisabled();

// Regex with unicode flag (for apostrophes, special chars)
await expect(page.getByText(/^You.re all set!$/u)).toBeVisible();

Always use the /u (unicode) flag on regex patterns to correctly handle special characters.

API mocking with page.route()

Basic mock

async function mockProducts(page: Page, response: unknown): Promise<void> {
  await page.route('**/api/products**', async (route) => {
    await route.fulfill({ json: response });
  });
}

Mock with different HTTP methods

async function mockPurchase(page: Page, purchaseId: string, response: unknown): Promise<void> {
  // Mock POST (create)
  await page.route('**/api/purchases', async (route) => {
    await route.fulfill({ json: { id: purchaseId } });
  });

  // Mock GET (status poll)
  await page.route(`**/api/purchases/${purchaseId}`, async (route) => {
    await route.fulfill({ json: response });
  });
}

Block external requests

A common pattern is to block all external requests and only allow requests to the app itself:

await page.route('**/*', async (route) => {
  const url = new URL(route.request().url());

  if (url.origin === appBaseUrl) {
    await route.continue();
  } else {
    await route.abort();
  }
});

Override existing mocks

Playwright uses last-registered-wins for route matching. Register a new route for the same pattern to override an earlier mock:

// Global fixture mocks /api/properties with defaults
// Your test overrides with custom data:
await page.route('**/api/properties/**', async (route) => {
  await route.fulfill({ json: customPropertyData });
});

Mock third-party services

async function setupExternalMocks(page: Page): Promise<void> {
  await page.route('https://analytics.example.com/**', async (route) => {
    await route.fulfill({ status: 200, body: '' });
  });

  await page.route('https://cdn.example.com/**', async (route) => {
    await route.fulfill({ status: 200, body: '', contentType: 'image/jpeg' });
  });
}

Creating test data fixtures

See references/fixtures.md for detailed patterns.

Variant pattern (simple features)

Use a base const object + spread for variants. Each test gets exactly the data shape it needs, and you can see what differs from the base at a glance:

export const itemBase = {
  id: 'test-item-id',
  name: 'Test Item',
  status: 'active',
  items: []
} as const;

export const itemWithProducts = {
  ...itemBase,
  items: [{
    productId: 'test-product-id',
    status: 'confirmed'
  }]
} as const;

Factory pattern (complex features)

When fixtures need many permutations with computed fields:

function createAccessKey(options: {
  readonly id: string;
  readonly type: 'code' | 'remote';
  readonly name: string;
  readonly code?: string | null;
}) {
  return {
    id: options.id,
    type: options.type,
    name: options.name,
    code: options.code ?? null,
    validFrom: '2024-01-01T00:00:00.000Z',
    validTo: '2099-12-31T23:59:59.000Z'
  } as const;
}

Factory functions stay private to the fixture file. Exported variants compose them.

Fixture data conventions

ConventionWhy
Use as const on every exported objectTypeScript narrows the type, catches typos
Use far-future dates in fixtures (e.g., year 2088)Won't expire during test lifetime
Use clearly fake IDs with consistent prefixesEasy to grep, obviously not real data
Spread from base, override only what mattersMakes test intent clear

API request testing

For testing server-side API endpoints directly, use Playwright's APIRequestContext — no browser needed.

Worker-scoped fixtures for authentication

Use worker-scoped fixtures instead of beforeAll + shared mutable let variables. Worker scope creates the context once per worker thread (same performance), eliminates shared mutable state, and integrates cleanly with Playwright's teardown lifecycle.

// tests/playwright/fixtures.ts
import { test as base, type APIRequestContext } from '@playwright/test'
import { appBaseUrl } from './constants'

interface WorkerFixtures {
  authedRequest: APIRequestContext;
}

export const test = base.extend<Record<never, never>, WorkerFixtures>({
  authedRequest: [
    async ({ playwright }, use) => {
      const request = await playwright.request.newContext({ baseURL: appBaseUrl })
      await request.post('/api/auth/create-session')
      await use(request)
      await request.dispose()
    },
    { scope: 'worker' },
  ],
})

Import test from this file in API test files. The fixture is available as {authedRequest} in the test callback.

Type-safe JSON parsing

APIResponse.json() returns Promise<any> (Playwright's Serializable = any). Assigning any directly to a typed variable triggers no-unsafe-assignment. Use unknown as the intermediate type, then parse with a validation library:

// ✅ Correct — breaks out of any safely
const raw: unknown = await response.json()
const body = v.parse(mySchema, raw)  // Valibot accepts unknown, returns typed result

// ❌ Wrong — casting any → specific type bypasses runtime check
const body = await response.json() as MyResponseType

// ❌ Wrong — no-await-expression-member: don't chain .json() onto an await
const raw: unknown = await (await request.get('/api/items')).json()

When using Valibot, split request and parse onto separate lines — Valibot's parse throws a descriptive error if the shape doesn't match, which makes test failures easy to diagnose.

What to assert in API tests

When a validation schema already enforces response shape, shape assertions add zero value — the schema throws before assertions are even reached. Focus on assertions TypeScript and schemas can't verify:

// ❌ Redundant when v.parse(schema, raw) already validates the shape
expect(body).toMatchObject({ id: expect.any(Number), name: expect.any(String) })

// ✅ Tests actual behavior — HTTP contract, correct data, filter logic, auth
expect(response.status()).toBe(200)
expect(body.name).toBe('MSR')
expect(body.items.length).toBeGreaterThan(0)
expect(filteredBody.items.every(item => item.category.slug === 'sleeping-pads')).toBe(true)

High-value API assertions: status codes, specific values (names, slugs, IDs confirming correct record), filter correctness, pagination boundaries, auth enforcement (401 without session).

Testing 401 / unauthenticated responses

Create an anonymous context inline — never reuse the authenticated fixture for negative auth tests:

test('returns 401 without session cookie', async ({ playwright }) => {
  const anonRequest = await playwright.request.newContext({ baseURL: appBaseUrl })
  const response = await anonRequest.get('/api/equipment/groups')

  expect(response.status()).toBe(401)

  await anonRequest.dispose()
})
# Run all Playwright tests
npx playwright test

# Run a specific test file
npx playwright test tests/playwright/product/checkout.test.ts

# Run with UI mode for debugging
npx playwright test --ui

# Run with headed browser
npx playwright test --headed

# Run with Playwright inspector/debug mode
npx playwright test --debug

# Open the last HTML report
npx playwright show-report

Check the project's package.json for available test scripts — many projects define shortcuts like test:playwright, test:e2e, or similar.

Validation checklist

Before considering an E2E test complete, verify:

  • test and expect imported from the project's fixture file (if one exists)
  • Only types imported from @playwright/test (e.g., type Page, type Locator)
  • Feature-specific fixtures use as const on all exported objects
  • Future dates used in fixture data
  • test.describe() groups related tests
  • Helper functions extracted for repeated navigation/assertion patterns
  • Multi-step flows use test.step() blocks
  • page.waitForRequest() set up BEFORE the triggering action
  • Regex patterns use /u flag
  • .first() used when multiple matching elements exist
  • No external services left unmocked (check console for blocked request warnings)
  • API tests: const raw: unknown = await response.json() — never assign any directly
  • API tests: Schema validation (Valibot/Zod) used; shape-only toMatchObject assertions removed
  • API tests: Auth tests use inline anonymous context, not the authenticated fixture
  • API tests: Worker-scoped fixtures used for authentication (not beforeAll + let)
  • Test runs successfully

Reference files

平台分布

Codex

39.02%
按下载量换算42

Claude

27.9%
按下载量换算30

Cursor

19.98%
按下载量换算21

Gemini CLI

8.81%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

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

安装前确认

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

继续浏览同类 Skills