SuperAPI AI 工具集

cypress-playwright-setup

测试与质量

查看项目

更新于 10-15 15:25

技能介绍

用途

该技能用于为 Web 应用配置完整的端到端(E2E)测试,可在 Cypress 与 Playwright 之间选择其一。目标是建立包含页面对象、测试夹具与 CI 集成的测试体系,覆盖用户旅程。

核心工作流

  1. 选择工具:Cypress 或 Playwright
  2. 配置项目:浏览器与测试设置
  3. 创建页面对象:可复用的选择器
  4. 编写测试:覆盖用户旅程
  5. 设置夹具(fixtures):测试数据
  6. 集成 CI:自动化测试

Playwright 设置

安装命令:

npm init playwright@latest

配置示例(playwright.config.ts)包含:testDir 指向 ./e2e、fullyParallel、CI 下 forbidOnly、CI 下重试 2 次、CI 下 workers 为 1、reporter 使用 html/json/junit、baseURL 默认 http://localhost:3000、trace 为 on-first-retry、screenshot 为 only-on-failure、video 为 retain-on-failure;projects 覆盖 chromium、firefox、webkit、Mobile Chrome(Pixel 5)、Mobile Safari(iPhone 12);webServer 使用 npm run start,url 为 http://localhost:3000,reuseExistingServer 在非 CI 下启用,timeout 为 120 秒。

页面对象模型:提供 BasePage 抽象类(含 goto、waitForLoad、getByTestId),以及 LoginPage(emailInput、passwordInput、submitButton、errorMessage、forgotPasswordLink,含 goto、login、expectError、expectLoginSuccess)与 DashboardPage(welcomeMessage、userMenu、logoutButton、sidebar,含 goto、logout、expectWelcome)。

测试示例(e2e/auth.spec.ts)覆盖:成功登录、无效凭据、空字段校验、忘记密码流程。

夹具(e2e/fixtures/auth.fixture.ts)通过 base.extend 提供 loginPage、dashboardPage、authenticatedPage(测试前自动登录)。

Cypress 设置

安装命令:

npm install -D cypress @testing-library/cypress
npx cypress open

配置示例(cypress.config.ts)包含:e2e 的 baseUrl 为 http://localhost:3000、viewportWidth 1280、viewportHeight 720、video 开启、screenshotOnRunFailure 开启、retries(runMode 2、openMode 0)、experimentalStudio 开启、setupNodeEvents;component 的 devServer 使用 react 框架与 vite 打包器。

支持命令(cypress/support/commands.ts):引入 @testing-library/cypress/add-commands,声明并实现 login(使用 cy.session)、getByTestId、mockApi(使用 cy.intercept)。

Cypress 测试示例(cypress/e2e/auth.cy.ts)覆盖:成功登录、无效凭据错误、必填字段校验。

API 模拟示例(cypress/e2e/products.cy.ts)覆盖:从 API 展示产品、优雅处理 API 错误、筛选产品。

CI 集成

提供 GitHub Actions 工作流(.github/workflows/e2e.yml),在 push 与 pull_request 到 main 分支时触发,包含两个 job:

  • playwright:checkout、setup-node(node 20、npm 缓存)、npm ci、npx playwright install --with-deps、npm run build、npx playwright test(CI=true)、上传 playwright-report 工件(保留 30 天)。
  • cypress:checkout、setup-node(node 20、npm 缓存)、npm ci、使用 cypress-io/github-action@v6(build、start、wait-on、browser chrome、record),环境变量 CYPRESS_RECORD_KEY 与 GITHUB_TOKEN,失败时上传 cypress/screenshots 工件。

无障碍测试

Playwright 使用 @axe-core/playwright 的 AxeBuilder 扫描首页与登录页,断言 violations 为空,可指定 wcag2a、wcag2aa 标签。

Cypress 使用 cypress-axe,通过 cy.injectAxe() 与 cy.checkA11y() 检查首页与登录表单。

最佳实践

  • 使用页面对象:选择器可维护
  • 使用测试 ID:元素选择稳定
  • 避免 sleep:使用正确的等待
  • 隔离测试:测试之间无依赖
  • 模拟外部 API:测试可靠且快速
  • 测试无障碍:包含 a11y 检查
  • 并行执行:加快 CI
  • 有意义的断言:期望清晰

输出清单

每个 E2E 设置应包含:Playwright/Cypress 配置、页面对象模型、自定义命令/夹具、API 模拟设置、认证处理、多浏览器测试、无障碍测试、CI 集成、报告配置、失败时截图/视频。

限制

资料未提供该技能的具体收费、价格、平台支持范围或效果数据,暂未提供。