cypress

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cypress

Cypress

Cypress is a next generation front end testing tool built for the modern web. It runs inside the browser (unlike Selenium/Playwright) which gives it native access to the DOM.
Cypress是为现代Web打造的下一代前端测试工具。它运行在浏览器内部(与Selenium/Playwright不同),这使其能够原生访问DOM。

When to Use

适用场景

  • Dev Experience: The interactive GUI is best-in-class for debugging.
  • Component Testing: Testing React/Vue/Angular components in isolation within a real browser.
  • Single Tab: Testing flows that happen in a single tab/window.
  • 开发体验:交互式GUI在调试方面表现一流。
  • 组件测试:在真实浏览器中独立测试React/Vue/Angular组件。
  • 单标签页:测试在单个标签页/窗口内完成的流程。

Quick Start

快速开始

javascript
describe("My First Test", () => {
  it("Visits the Kitchen Sink", () => {
    cy.visit("https://example.cypress.io");
    cy.contains("type").click();
    cy.url().should("include", "/commands/actions");
    cy.get(".action-email")
      .type("fake@email.com")
      .should("have.value", "fake@email.com");
  });
});
javascript
describe("My First Test", () => {
  it("Visits the Kitchen Sink", () => {
    cy.visit("https://example.cypress.io");
    cy.contains("type").click();
    cy.url().should("include", "/commands/actions");
    cy.get(".action-email")
      .type("fake@email.com")
      .should("have.value", "fake@email.com");
  });
});

Core Concepts

核心概念

Chaining

链式调用

Cypress commands run serially.
cy.get().click().should()
reads like a story.
Cypress命令按顺序执行。
cy.get().click().should()
的写法就像讲故事一样直观。

Automatic Retries

自动重试

Cypress automatically retries assertions until they pass or timeout.
cy.get('.todo-list li').should('have.length', 2)
will retry until the list has 2 items or 4 seconds elapse.
Cypress会自动重试断言,直到断言通过或超时。
cy.get('.todo-list li').should('have.length', 2)
会一直重试,直到列表有2个项目或4秒超时。

Stubbing

存根(Stubbing)

Because it runs in-browser, intercepting network requests (
cy.intercept
) is fast and reliable.
由于它运行在浏览器中,拦截网络请求(
cy.intercept
)既快速又可靠。

Best Practices (2025)

2025年最佳实践

Do:
  • Use
    cy.intercept
    : Wait for network calls to finish before asserting UI.
    cy.wait('@apiCall')
    .
  • Use Custom Commands: Extract repetitive logic (login) into
    cy.login()
    .
  • Use Data Test Attributes:
    data-cy="submit-btn"
    allows you to change CSS/JS without breaking tests.
Don't:
  • Don't use
    wait(number)
    : Never hard-code waits. Wait for routes or elements.
  • Don't test 3rd party sites: Cypress is for your app. It has safeguards that make testing Google/Github hard.
建议
  • 使用
    cy.intercept
    :在断言UI之前等待网络请求完成。
    cy.wait('@apiCall')
  • 使用自定义命令:将重复逻辑(如登录)提取为
    cy.login()
  • 使用数据测试属性
    data-cy="submit-btn"
    允许你修改CSS/JS而不破坏测试。
不建议
  • 不要使用
    wait(number)
    :永远不要硬编码等待时间。应等待路由或元素。
  • 不要测试第三方网站:Cypress是为你的应用设计的。它的安全机制会让测试Google/Github等网站变得困难。

References

参考资料