init
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseInitialize 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 subagent to scan the project:
Explore- Check for framework (React, Next.js, Vue, Angular, Svelte)
package.json - Check for → use TypeScript; otherwise JavaScript
tsconfig.json - Check if Playwright is already installed (in dependencies)
@playwright/test - Check for existing test directories (,
tests/,e2e/)__tests__/ - Check for existing CI config (,
.github/workflows/).gitlab-ci.yml
使用子代理扫描项目:
Explore- 检查以确定使用的框架(React、Next.js、Vue、Angular、Svelte)
package.json - 检查是否存在→ 存在则使用TypeScript,否则使用JavaScript
tsconfig.json - 检查是否已安装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 -- --quietOr 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 chromium3. Generate playwright.config.ts
playwright.config.ts3. 生成playwright.config.ts
playwright.config.tsAdapt 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 to
baseURLhttp://localhost:5173 - Change to
webServer.commandnpm run dev
Vue/Nuxt:
- Change to
baseURLhttp://localhost:3000 - Change to
webServer.commandnpm run dev
Angular:
- Change to
baseURLhttp://localhost:4200 - Change to
webServer.commandnpm run start
No framework detected:
- Omit block
webServer - Set from user input or leave as placeholder
baseURL
根据检测到的框架进行适配:
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):
- 将修改为
baseURLhttp://localhost:5173 - 将修改为
webServer.commandnpm run dev
Vue/Nuxt:
- 将修改为
baseURLhttp://localhost:3000 - 将修改为
webServer.commandnpm run dev
Angular:
- 将修改为
baseURLhttp://localhost:4200 - 将修改为
webServer.commandnpm 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 teste2e/
├── 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 exists, create :
.github/workflows/playwright.ymlyaml
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: 30If exists, add a Playwright stage instead.
.gitlab-ci.yml如果目录存在,创建:
.github/workflows/playwright.ymlyaml
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如果存在,则添加一个Playwright阶段。
.gitlab-ci.yml7. Update .gitignore
.gitignore7. 更新.gitignore
.gitignoreAppend 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 scripts:
package.jsonjson
{
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:debug": "playwright test --debug"
}在的scripts中添加:
package.jsonjson
{
"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 testReport 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: or
npx playwright testnpm run test:e2e
确认已创建的内容:
- 配置文件路径及关键设置
- 测试目录及示例测试用例
- CI工作流(如适用)
- 添加的npm脚本
- 运行方式:或
npx playwright testnpm run test:e2e