generate

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Generate Playwright Tests

生成Playwright测试

Generate production-ready Playwright tests from a user story, URL, component name, or feature description.
根据用户故事、URL、组件名称或功能描述生成可用于生产环境的Playwright测试。

Input

输入

$ARGUMENTS
contains what to test. Examples:
  • "user can log in with email and password"
  • "the checkout flow"
  • "src/components/UserProfile.tsx"
  • "the search page with filters"
$ARGUMENTS
包含要测试的内容。示例:
  • "用户可以使用邮箱和密码登录"
  • "结账流程"
  • "src/components/UserProfile.tsx"
  • "带筛选器的搜索页面"

Steps

步骤

1. Understand the Target

1. 明确测试目标

Parse
$ARGUMENTS
to determine:
  • User story: Extract the behavior to verify
  • Component path: Read the component source code
  • Page/URL: Identify the route and its elements
  • Feature name: Map to relevant app areas
解析
$ARGUMENTS
以确定:
  • 用户故事:提取需要验证的行为
  • 组件路径:读取组件源代码
  • 页面/URL:识别路由及其元素
  • 功能名称:映射到应用的相关区域

2. Explore the Codebase

2. 探索代码库

Use the
Explore
subagent to gather context:
  • Read
    playwright.config.ts
    for
    testDir
    ,
    baseURL
    ,
    projects
  • Check existing tests in
    testDir
    for patterns, fixtures, and conventions
  • If a component path is given, read the component to understand its props, states, and interactions
  • Check for existing page objects in
    pages/
  • Check for existing fixtures in
    fixtures/
  • Check for auth setup (
    auth.setup.ts
    or
    storageState
    config)
使用
Explore
子代理收集上下文:
  • 读取
    playwright.config.ts
    获取
    testDir
    baseURL
    projects
    配置
  • 检查
    testDir
    中的现有测试,了解测试模式、fixture和约定
  • 如果提供了组件路径,读取组件以理解其props、状态和交互逻辑
  • 检查
    pages/
    目录下的现有页面对象
  • 检查
    fixtures/
    目录下的现有fixture
  • 检查认证设置(
    auth.setup.ts
    storageState
    配置)

3. Select Templates

3. 选择模板

Check
templates/
in this plugin for matching patterns:
If testing...Load template from
Login/auth flow
templates/auth/login.md
CRUD operations
templates/crud/
Checkout/payment
templates/checkout/
Search/filter UI
templates/search/
Form submission
templates/forms/
Dashboard/data
templates/dashboard/
Settings page
templates/settings/
Onboarding flow
templates/onboarding/
API endpoints
templates/api/
Accessibility
templates/accessibility/
Adapt the template to the specific app — replace
{{placeholders}}
with actual selectors, URLs, and data.
查看此插件的
templates/
目录,匹配对应模式:
测试场景...加载模板路径
登录/认证流程
templates/auth/login.md
CRUD操作
templates/crud/
结账/支付流程
templates/checkout/
搜索/筛选UI
templates/search/
表单提交
templates/forms/
仪表盘/数据页面
templates/dashboard/
设置页面
templates/settings/
新用户引导流程
templates/onboarding/
API接口
templates/api/
可访问性
templates/accessibility/
根据具体应用调整模板——将
{{placeholders}}
替换为实际的选择器、URL和数据。

4. Generate the Test

4. 生成测试用例

Follow these rules:
Structure:
typescript
import { test, expect } from '@playwright/test';
// Import custom fixtures if the project uses them

test.describe('Feature Name', () => {
  // Group related behaviors

  test('should <expected behavior>', async ({ page }) => {
    // Arrange: navigate, set up state
    // Act: perform user action
    // Assert: verify outcome
  });
});
Locator priority (use the first that works):
  1. getByRole()
    — buttons, links, headings, form elements
  2. getByLabel()
    — form fields with labels
  3. getByText()
    — non-interactive text content
  4. getByPlaceholder()
    — inputs with placeholder text
  5. getByTestId()
    — when semantic options aren't available
Assertions — always web-first:
typescript
// GOOD — auto-retries
await expect(page.getByRole('heading')).toBeVisible();
await expect(page.getByRole('alert')).toHaveText('Success');

// BAD — no retry
const text = await page.textContent('.msg');
expect(text).toBe('Success');
Never use:
  • page.waitForTimeout()
  • page.$(selector)
    or
    page.$$(selector)
  • Bare CSS selectors unless absolutely necessary
  • page.evaluate()
    for things locators can do
Always include:
  • Descriptive test names that explain the behavior
  • Error/edge case tests alongside happy path
  • Proper
    await
    on every Playwright call
  • baseURL
    -relative navigation (
    page.goto('/')
    not
    page.goto('http://...')
    )
遵循以下规则:
结构:
typescript
import { test, expect } from '@playwright/test';
// 如果项目使用自定义fixture,导入它们

test.describe('功能名称', () => {
  // 分组相关行为

  test('应该<预期行为>', async ({ page }) => {
    // 准备:导航到页面,设置状态
    // 执行:执行用户操作
    // 断言:验证结果
  });
});
定位器优先级(优先使用第一个可用的):
  1. getByRole()
    —— 按钮、链接、标题、表单元素
  2. getByLabel()
    —— 带标签的表单字段
  3. getByText()
    —— 非交互式文本内容
  4. getByPlaceholder()
    —— 带占位符的输入框
  5. getByTestId()
    —— 当语义化选项不可用时使用
断言 —— 始终使用Web-first断言:
typescript
// 推荐——自动重试
await expect(page.getByRole('heading')).toBeVisible();
await expect(page.getByRole('alert')).toHaveText('Success');

// 不推荐——无重试机制
const text = await page.textContent('.msg');
expect(text).toBe('Success');
禁止使用:
  • page.waitForTimeout()
  • page.$(selector)
    page.$$(selector)
  • 除非绝对必要,否则不要使用纯CSS选择器
  • 对于定位器可以完成的操作,不要使用
    page.evaluate()
必须包含:
  • 描述性的测试名称,解释测试的行为
  • 除了正常流程测试外,还要包含错误/边界情况测试
  • 每个Playwright调用都要正确使用
    await
  • 相对于
    baseURL
    的导航(使用
    page.goto('/')
    而非
    page.goto('http://...')

5. Match Project Conventions

5. 匹配项目约定

  • If project uses TypeScript → generate
    .spec.ts
  • If project uses JavaScript → generate
    .spec.js
    with
    require()
    imports
  • If project has page objects → use them instead of inline locators
  • If project has custom fixtures → import and use them
  • If project has a test data directory → create test data files there
  • 如果项目使用TypeScript → 生成
    .spec.ts
    文件
  • 如果项目使用JavaScript → 生成
    .spec.js
    文件,使用
    require()
    导入
  • 如果项目使用页面对象 → 使用页面对象而非内联定位器
  • 如果项目有自定义fixture → 导入并使用它们
  • 如果项目有测试数据目录 → 在该目录下创建测试数据文件

6. Generate Supporting Files (If Needed)

6. 生成支持文件(如有需要)

  • Page object: If the test touches 5+ unique locators on one page, create a page object
  • Fixture: If the test needs shared setup (auth, data), create or extend a fixture
  • Test data: If the test uses structured data, create a JSON file in
    test-data/
  • 页面对象:如果测试在一个页面上涉及5个以上唯一定位器,创建页面对象
  • Fixture:如果测试需要共享设置(认证、数据),创建或扩展fixture
  • 测试数据:如果测试使用结构化数据,在
    test-data/
    目录下创建JSON文件

7. Verify

7. 验证

Run the generated test:
bash
npx playwright test <generated-file> --reporter=list
If it fails:
  1. Read the error
  2. Fix the test (not the app)
  3. Run again
  4. If it's an app issue, report it to the user
运行生成的测试:
bash
npx playwright test <generated-file> --reporter=list
如果测试失败:
  1. 读取错误信息
  2. 修复测试(而非修改应用)
  3. 重新运行
  4. 如果是应用问题,向用户报告

Output

输出

  • Generated test file(s) with path
  • Any supporting files created (page objects, fixtures, data)
  • Test run result
  • Coverage note: what behaviors are now tested
  • 生成的测试文件及路径
  • 创建的所有支持文件(页面对象、fixture、数据文件)
  • 测试运行结果
  • 覆盖说明:现在已测试哪些行为