adding-e2e-tests
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdd E2E Tests (Playwright)
添加端到端测试(Playwright)
Use this skill when the user asks to add end-to-end tests, browser tests, integration tests, or set up Playwright.
当用户要求添加端到端测试、浏览器测试、集成测试或搭建Playwright时,可使用此技能。
Steps
步骤
-
Install Playwrightbash
npm init playwright@latestThis creates, aplaywright.config.tsdirectory, and installs browsers. If the project already has a test runner, install manually:tests/bashnpm install -D @playwright/test npx playwright install -
Configure
playwright.config.ts-
Setto the local dev server URL (e.g.
baseURL).http://localhost:3000 -
Configureto start the dev server automatically:
webServertswebServer: { command: "npm run dev", url: "http://localhost:3000", reuseExistingServer: !process.env.CI, }, -
Enable only chromium for local dev speed; enable all browsers in CI.
-
-
Create a smoke test — write a basic test that verifies the app loads:ts
import { test, expect } from "@playwright/test"; test("homepage loads", async ({ page }) => { await page.goto("/"); await expect(page).toHaveTitle(/.+/); }); -
Add page object pattern (optional) — for larger apps, create adirectory with page objects that encapsulate selectors and actions.
tests/pages/ -
Add npm scriptsjson
{ "test:e2e": "playwright test", "test:e2e:ui": "playwright test --ui" } -
Add to
.gitignoretest-results/ playwright-report/ blob-report/ -
CI integration — add a GitHub Actions step that runsthen
npx playwright install --with-deps. Use the officialnpm run test:e2eto save the HTML report on failure.actions/upload-artifact
-
安装Playwrightbash
npm init playwright@latest这会创建文件、playwright.config.ts目录并安装浏览器。如果项目已有测试运行器,请手动安装:tests/bashnpm install -D @playwright/test npx playwright install -
配置
playwright.config.ts-
将设置为本地开发服务器地址(例如
baseURL)。http://localhost:3000 -
配置以自动启动开发服务器:
webServertswebServer: { command: "npm run dev", url: "http://localhost:3000", reuseExistingServer: !process.env.CI, }, -
本地开发时仅启用Chromium以提升速度;在CI环境中启用所有浏览器。
-
-
创建冒烟测试 — 编写一个验证应用能否加载的基础测试:ts
import { test, expect } from "@playwright/test"; test("homepage loads", async ({ page }) => { await page.goto("/"); await expect(page).toHaveTitle(/.+/); }); -
添加页面对象模式(可选) — 对于大型应用,创建目录,其中的页面对象封装了选择器和操作。
tests/pages/ -
添加npm脚本json
{ "test:e2e": "playwright test", "test:e2e:ui": "playwright test --ui" } -
添加到
.gitignoretest-results/ playwright-report/ blob-report/ -
CI集成 — 添加GitHub Actions步骤,先运行,再执行
npx playwright install --with-deps。使用官方npm run test:e2e在测试失败时保存HTML报告。actions/upload-artifact
Notes
注意事项
- Use attributes for selectors instead of CSS classes.
data-testid - Use to group related tests.
test.describe - Run to record tests interactively.
npx playwright codegen
- 使用属性作为选择器,而非CSS类。
data-testid - 使用对相关测试进行分组。
test.describe - 运行以交互式方式录制测试。
npx playwright codegen