init

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Initialize Playwright Project

初始化Playwright项目

Set up a production-ready Playwright testing environment. Detect the framework, generate config, folder structure, example test, and CI workflow.
搭建生产可用的Playwright测试环境。自动检测框架,生成配置文件、文件夹结构、示例测试用例以及CI工作流。

Steps

步骤

1. Analyze the Project

1. 分析项目

Use the
Explore
subagent to scan the project:
  • Check
    package.json
    for framework (React, Next.js, Vue, Angular, Svelte)
  • Check for
    tsconfig.json
    → use TypeScript; otherwise JavaScript
  • Check if Playwright is already installed (
    @playwright/test
    in dependencies)
  • Check for existing test directories (
    tests/
    ,
    e2e/
    ,
    __tests__/
    )
  • Check for existing CI config (
    .github/workflows/
    ,
    .gitlab-ci.yml
    )
使用
Explore
子代理扫描项目:
  • 检查
    package.json
    以确定使用的框架(React、Next.js、Vue、Angular、Svelte)
  • 检查是否存在
    tsconfig.json
    → 存在则使用TypeScript,否则使用JavaScript
  • 检查是否已安装Playwright(依赖中是否包含
    @playwright/test
  • 检查是否存在现有测试目录(
    tests/
    e2e/
    __tests__/
  • 检查是否存在现有CI配置(
    .github/workflows/
    .gitlab-ci.yml

2. Install Playwright

2. 安装Playwright

If not already installed:
bash
npm init playwright@latest -- --quiet
Or if the user prefers manual setup:
bash
npm install -D @playwright/test
npx playwright install --with-deps chromium
如果尚未安装:
bash
npm init playwright@latest -- --quiet
或者如果用户偏好手动安装:
bash
npm install -D @playwright/test
npx playwright install --with-deps chromium

3. Generate
playwright.config.ts

3. 生成
playwright.config.ts

Adapt to the detected framework:
Next.js:
typescript
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './e2e',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 1 : undefined,
  reporter: [
    ['html', { open: 'never' }],
    ['list'],
  ],
  use: {
    baseURL: 'http://localhost:3000',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit', use: { ...devices['Desktop Safari'] } },
  ],
  webServer: {
    command: 'npm run dev',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
  },
});
React (Vite):
  • Change
    baseURL
    to
    http://localhost:5173
  • Change
    webServer.command
    to
    npm run dev
Vue/Nuxt:
  • Change
    baseURL
    to
    http://localhost:3000
  • Change
    webServer.command
    to
    npm run dev
Angular:
  • Change
    baseURL
    to
    http://localhost:4200
  • Change
    webServer.command
    to
    npm run start
No framework detected:
  • Omit
    webServer
    block
  • Set
    baseURL
    from user input or leave as placeholder
根据检测到的框架进行适配:
Next.js:
typescript
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './e2e',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 1 : undefined,
  reporter: [
    ['html', { open: 'never' }],
    ['list'],
  ],
  use: {
    baseURL: 'http://localhost:3000',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit', use: { ...devices['Desktop Safari'] } },
  ],
  webServer: {
    command: 'npm run dev',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
  },
});
React (Vite):
  • baseURL
    修改为
    http://localhost:5173
  • webServer.command
    修改为
    npm run dev
Vue/Nuxt:
  • baseURL
    修改为
    http://localhost:3000
  • webServer.command
    修改为
    npm run dev
Angular:
  • baseURL
    修改为
    http://localhost:4200
  • webServer.command
    修改为
    npm run start
未检测到框架:
  • 省略
    webServer
  • 根据用户输入设置
    baseURL
    ,或保留为占位符

4. Create Folder Structure

4. 创建文件夹结构

e2e/
├── fixtures/
│   └── index.ts          # Custom fixtures
├── pages/
│   └── .gitkeep          # Page object models
├── test-data/
│   └── .gitkeep          # Test data files
└── example.spec.ts       # First example test
e2e/
├── fixtures/
│   └── index.ts          # 自定义fixtures
├── pages/
│   └── .gitkeep          # 页面对象模型
├── test-data/
│   └── .gitkeep          # 测试数据文件
└── example.spec.ts       # 首个示例测试用例

5. Generate Example Test

5. 生成示例测试用例

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

test.describe('Homepage', () => {
  test('should load successfully', async ({ page }) => {
    await page.goto('/');
    await expect(page).toHaveTitle(/.+/);
  });

  test('should have visible navigation', async ({ page }) => {
    await page.goto('/');
    await expect(page.getByRole('navigation')).toBeVisible();
  });
});
typescript
import { test, expect } from '@playwright/test';

test.describe('首页', () => {
  test('应成功加载', async ({ page }) => {
    await page.goto('/');
    await expect(page).toHaveTitle(/.+/);
  });

  test('导航栏应可见', async ({ page }) => {
    await page.goto('/');
    await expect(page.getByRole('navigation')).toBeVisible();
  });
});

6. Generate CI Workflow

6. 生成CI工作流

If
.github/workflows/
exists, create
playwright.yml
:
yaml
name: Playwright Tests

on:
  push:
    branches: [main, dev]
  pull_request:
    branches: [main, dev]

jobs:
  test:
    timeout-minutes: 60
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
      - name: Install dependencies
        run: npm ci
      - name: Install Playwright Browsers
        run: npx playwright install --with-deps
      - name: Run Playwright tests
        run: npx playwright test
      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 30
If
.gitlab-ci.yml
exists, add a Playwright stage instead.
如果
.github/workflows/
目录存在,创建
playwright.yml
yaml
name: Playwright Tests

on:
  push:
    branches: [main, dev]
  pull_request:
    branches: [main, dev]

jobs:
  test:
    timeout-minutes: 60
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
      - name: 安装依赖
        run: npm ci
      - name: 安装Playwright浏览器
        run: npx playwright install --with-deps
      - name: 运行Playwright测试
        run: npx playwright test
      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 30
如果
.gitlab-ci.yml
存在,则添加一个Playwright阶段。

7. Update
.gitignore

7. 更新
.gitignore

Append if not already present:
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
如果以下内容尚未存在,则追加:
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/

8. Add npm Scripts

8. 添加npm脚本

Add to
package.json
scripts:
json
{
  "test:e2e": "playwright test",
  "test:e2e:ui": "playwright test --ui",
  "test:e2e:debug": "playwright test --debug"
}
package.json
的scripts中添加:
json
{
  "test:e2e": "playwright test",
  "test:e2e:ui": "playwright test --ui",
  "test:e2e:debug": "playwright test --debug"
}

9. Verify Setup

9. 验证搭建结果

Run the example test:
bash
npx playwright test
Report the result. If it fails, diagnose and fix before completing.
运行示例测试用例:
bash
npx playwright test
报告运行结果。如果测试失败,先诊断并修复问题再完成整个流程。

Output

输出

Confirm what was created:
  • Config file path and key settings
  • Test directory and example test
  • CI workflow (if applicable)
  • npm scripts added
  • How to run:
    npx playwright test
    or
    npm run test:e2e
确认已创建的内容:
  • 配置文件路径及关键设置
  • 测试目录及示例测试用例
  • CI工作流(如适用)
  • 添加的npm脚本
  • 运行方式:
    npx playwright test
    npm run test:e2e