在项目中设置 Playwright。当用户说“set up playwright”、“add e2e tests”、“configure playwright”、“testing setup”、“init playwright”或“add test infrastructure”时使用。
建立一个生产就绪的 Playwright 测试环境。检测框架,生成配置、文件夹结构、示例测试和 CI 工作流。
使用 Explore 子代理扫描项目:
package.json 中的框架(React, Next.js, Vue, Angular, Svelte)tsconfig.json → 使用 TypeScript;否则使用 JavaScript@playwright/test)tests/、e2e/、__tests__/).github/workflows/、.gitlab-ci.yml)如果尚未安装:
npm init playwright@latest -- --quiet
或者如果用户偏好手动设置:
npm install -D @playwright/test
npx playwright install --with-deps chromium
playwright.config.ts适配检测到的框架:
Next.js:
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:5173webServer.command 更改为 npm run devVue/Nuxt:
baseURL 更改为 http://localhost:3000webServer.command 更改为 npm run devAngular:
baseURL 更改为 http://localhost:4200webServer.command 更改为 npm run start未检测到框架:
webServer 块baseURL 或保留为占位符e2e/
├── fixtures/
│ └── index.ts # 自定义 fixture
├── pages/
│ └── .gitkeep # 页面对象模型 (Page object models)
├── test-data/
│ └── .gitkeep # 测试数据文件
└── example.spec.ts # 第一个示例测试
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();
});
});
如果存在 .github/workflows/,则创建 playwright.yml: