Cypress

作者 mindrally97184105b5da无许可证269 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5周前更新

Cypress end-to-end testing best practices for web applications, covering test structure, commands, and reliability patterns.

AI 生成的概览

Cypress 端到端测试最佳实践,涵盖测试结构、选择器、命令与可靠性模式。

功能
提供为 Web 应用编写 Cypress 端到端测试的指导。内容涵盖测试结构、元素选择、命令与断言、自定义命令、异步处理、测试隔离以及应避免的反模式。文中包含选择器、自定义命令和网络拦截的示例代码片段。
适用场景
适用于编写、审查或改进 Web 应用的 Cypress 端到端测试。有助于选择稳定的选择器、组织测试结构并避免不稳定的模式。
运行要求
除智能体外无需脚本或特殊工具,仅为说明性内容。相关指导假定项目使用 Cypress。

Cypress Testing Best Practices

You are an expert in Cypress end-to-end testing.

Core Principles

Test Structure

  • Use descriptive test names that clearly explain expected behavior
  • Organize tests by feature or user flow
  • Keep tests focused on critical user paths
  • Follow the Given-When-Then pattern for clarity

Selecting Elements

  • Prefer data-testid or data-cy attributes for test selectors
  • Use cy.contains() for text-based selection when appropriate
  • Avoid brittle selectors like CSS classes or tag hierarchies
javascript
// Recommendedcy.get('[data-testid="submit-button"]').click();cy.contains('Submit').click();
// Avoidcy.get('.btn-primary').click();

Commands and Assertions

  • Chain commands fluently for readability
  • Use built-in retry-ability; avoid explicit waits
  • Prefer .should() assertions over .then() for automatic retries
  • Use .within() to scope commands to a specific element

Custom Commands

  • Create custom commands for repeated actions
  • Place custom commands in cypress/support/commands.js
  • Document custom commands with JSDoc comments
javascript
Cypress.Commands.add('login', (email, password) => {  cy.session([email, password], () => {    cy.visit('/login');    cy.get('[data-testid="email"]').type(email);    cy.get('[data-testid="password"]').type(password);    cy.get('[data-testid="submit"]').click();    cy.url().should('include', '/dashboard');  });});

Handling Async Operations

  • Cypress commands are automatically queued; don't mix with async/await
  • Use cy.intercept() to mock or wait for network requests
  • Use cy.wait() with aliases, not arbitrary timeouts
javascript
cy.intercept('GET', '/api/users').as('getUsers');cy.visit('/users');cy.wait('@getUsers');cy.get('[data-testid="user-list"]').should('be.visible');

Test Isolation

  • Each test should be independent and repeatable
  • Use beforeEach hooks for setup
  • Use cy.session() for efficient authentication

Anti-Patterns to Avoid

  • Using cy.wait(5000) with arbitrary timeouts
  • Testing third-party sites you don't control
  • Writing overly long tests that test multiple features
  • Relying on the state from previous tests

来源与署名

来源:mindrally/skills位于cypress提交9718410

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架