cypress-automation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<objective> Production-grade Cypress test suites in TypeScript. The failure this prevents: tests written as if Cypress commands ran synchronously (storing `cy.get()` in a variable, `await cy.click()`), and tests that flake because they wait on `cy.wait(3000)` instead of a network alias. This skill covers the mental model (command queue, retry-ability), project structure, custom commands, network control with `cy.intercept`, component testing, cross-origin auth with `cy.origin`, and Cypress Cloud / CI integration. </objective>
<objective> 使用TypeScript构建生产级Cypress测试套件。本技能可避免的问题:将Cypress命令当作同步代码编写(例如将`cy.get()`的结果存储到变量中、使用`await cy.click()`),以及因使用`cy.wait(3000)`而非网络别名等待导致的不稳定测试。本技能涵盖核心思维模型(命令队列、重试机制)、项目结构、自定义命令、基于`cy.intercept`的网络控制、组件测试、基于`cy.origin`的跨域认证,以及Cypress Cloud/CI集成。 </objective>

Quick Route

快速导航

You need to...Go to
Write an E2E spec (load, intercept, assert)Core Principles +
references/intercept-patterns.md
Add a typed custom command /
cy.session
login
Custom Commands +
references/config-and-commands.md
Mount and test a single componentComponent Testing +
references/component-and-fixtures.md
Scaffold
cypress.config.ts
/ project layout
Project Structure +
references/config-and-commands.md
Stub, spy, simulate errors, or poll an APIcy.intercept Patterns +
references/intercept-patterns.md
Run in CI / parallelize on Cypress CloudCI Integration +
references/ci-recipes.md
Handle an SSO / OAuth redirectCross-Origin Flows +
references/intercept-patterns.md

你需要...查看位置
编写E2E测试用例(加载、拦截、断言)核心原则 +
references/intercept-patterns.md
添加类型化自定义命令 /
cy.session
登录
自定义命令 +
references/config-and-commands.md
挂载并测试单个组件组件测试 +
references/component-and-fixtures.md
初始化
cypress.config.ts
/ 项目布局
项目结构 +
references/config-and-commands.md
存根、监听、模拟错误或轮询APIcy.intercept模式 +
references/intercept-patterns.md
在CI中运行 / 在Cypress Cloud中并行执行CI集成 +
references/ci-recipes.md
处理SSO/OAuth重定向跨域流程 +
references/intercept-patterns.md

Discovery Questions

调研问题

Check
.agents/qa-project-context.md
first -- if it exists, use it and skip questions already answered there.
  1. Component testing, E2E, or both? Component testing mounts individual components in isolation; E2E tests the full app through the browser. Most projects need both. Component testing requires a framework-specific mount (React, Vue, Angular, Svelte).
  2. Cypress Cloud? Cloud provides parallelization, flake detection, analytics, Test Replay, and the AI add-on. If the team uses it, configure
    projectId
    and the record key. If not, everything runs locally or in CI without Cloud.
  3. TypeScript? Strongly recommended and the default here -- Cypress supports it natively. All examples use TypeScript.
  4. Framework and bundler? React + Vite, Next.js + Webpack, Vue + Vite, Angular -- component-testing config depends on this.
  5. Cross-origin auth? If login redirects to a separate domain (SSO, OAuth provider), you need
    cy.origin
    . Note it now so the login command is built for it.
  6. Existing suite or fresh start? If migrating, start with the flakiest or most critical tests, not a big-bang rewrite (see
    test-migration
    ).

首先查看
.agents/qa-project-context.md
——如果该文件存在,使用其中内容并跳过已回答的问题。
  1. 组件测试、E2E测试,还是两者都需要? 组件测试会单独隔离挂载组件;E2E测试通过浏览器测试完整应用。大多数项目两者都需要。组件测试需要特定框架的挂载方法(React、Vue、Angular、Svelte)。
  2. 是否使用Cypress Cloud? Cloud提供并行执行、不稳定测试检测、分析、Test Replay以及AI附加功能。如果团队使用它,需配置
    projectId
    和记录密钥。如果不使用,所有测试将在本地或CI中运行,无需Cloud。
  3. 是否使用TypeScript? 强烈推荐,且为本技能的默认选择——Cypress原生支持TypeScript。所有示例均使用TypeScript。
  4. 使用的框架和打包工具? React + Vite、Next.js + Webpack、Vue + Vite、Angular——组件测试配置取决于此。
  5. 是否存在跨域认证? 如果登录重定向到其他域名(SSO、OAuth提供商),则需要使用
    cy.origin
    。请提前记录,以便登录命令适配该场景。
  6. 已有测试套件还是从零开始? 如果是迁移,请从最不稳定或最关键的测试开始,不要一次性重写所有测试(详见
    test-migration
    )。

Core Principles

核心原则

1. Commands Are Enqueued, Not Executed Immediately

1. 命令会被加入队列,而非立即执行

The single most important concept. Cypress commands (
cy.get
,
cy.click
,
cy.type
) do not execute when called -- they are added to a queue and run serially, asynchronously. You cannot use
async/await
with Cypress commands, and you cannot store the return value in a variable.
typescript
// WRONG -- this looks synchronous but is not
const button = cy.get('[data-testid="submit"]'); // button is a Chainable, not an element
button.click(); // works only by accident, via chaining

// CORRECT -- chain commands; use .then() when you need a value
cy.get('[data-testid="submit"]').click();

cy.get('[data-testid="price"]').invoke('text').then((text) => {
  const price = parseFloat(text.replace('$', ''));
  expect(price).to.be.greaterThan(0);
});
这是最重要的概念。Cypress命令(
cy.get
cy.click
cy.type
)在调用时不会立即执行——它们会被加入队列,然后串行、异步运行。不能对Cypress命令使用
async/await
,也不能将返回值存储到变量中。
typescript
// 错误写法——看似同步,但实际并非如此
const button = cy.get('[data-testid="submit"]'); // button是Chainable对象,而非DOM元素
button.click(); // 仅通过链式调用偶然生效

// 正确写法——链式调用;需要值时使用.then()
cy.get('[data-testid="submit"]').click();

cy.get('[data-testid="price"]').invoke('text').then((text) => {
  const price = parseFloat(text.replace('$', ''));
  expect(price).to.be.greaterThan(0);
});

2. Retry-ability Is Built-In (For Queries, Not Actions)

2. 重试机制内置(仅适用于查询,不适用于操作)

Cypress automatically retries queries (
cy.get
,
cy.find
,
cy.contains
) and assertions until they pass or time out. It does not retry actions (
cy.click
,
cy.type
,
cy.select
):
  • cy.get('.loading').should('not.exist')
    waits for the indicator to disappear
  • cy.get('.item').should('have.length', 5)
    waits for 5 items
  • cy.click()
    executes once -- if the element is not actionable, it fails
Cypress会自动重试查询命令
cy.get
cy.find
cy.contains
)和断言,直到它们通过或超时。但不会重试操作命令
cy.click
cy.type
cy.select
):
  • cy.get('.loading').should('not.exist')
    会等待加载指示器消失
  • cy.get('.item').should('have.length', 5)
    会等待5个元素加载完成
  • cy.click()
    仅执行一次——如果元素不可操作,测试会失败

3. Network Control with cy.intercept

3. 使用cy.intercept进行网络控制

cy.intercept
intercepts HTTP requests at the network layer -- stub responses, wait for requests to complete, assert on request bodies. Mastering it is the difference between flaky and stable tests. Always wait on a network alias or a DOM assertion, never a fixed
cy.wait(ms)
.
cy.intercept
在网络层拦截HTTP请求——可存根响应、等待请求完成、断言请求体。掌握它是区分不稳定测试与稳定测试的关键。始终等待网络别名或DOM断言,绝不要使用固定时长的
cy.wait(ms)

4. Isolation: Each Test Starts Clean

4. 隔离性:每个测试从干净状态开始

Every
it()
runs in fresh browser state -- Cypress clears cookies, localStorage, and sessionStorage between tests by default. Tests must not depend on other tests' state or order. Use
beforeEach
for shared setup, not inter-test dependencies.
每个
it()
都会在全新的浏览器状态下运行——默认情况下,Cypress会在测试之间清除Cookie、localStorage和sessionStorage。测试不能依赖其他测试的状态或执行顺序。使用
beforeEach
进行共享设置,不要在测试间建立依赖。

5. Data Attributes for Test Selectors

5. 使用数据属性作为测试选择器

Use
data-testid
,
data-cy
, or
data-test
. They survive CSS refactors, class renames, and localization. Configure the preferred attribute in
cypress.config.ts
.

使用
data-testid
data-cy
data-test
。它们能在CSS重构、类名修改和本地化操作中保留下来。可在
cypress.config.ts
中配置首选属性。

Project Structure & Configuration

项目结构与配置

Standard layout splits
e2e/
,
component/
,
fixtures/
, and
support/
, with
cypress.config.ts
at the root configuring both runners. Key config choices:
baseUrl
from env (never hardcode for CI), explicit viewport,
retries.runMode: 2
for CI, and the framework/bundler pair under
component.devServer
. Component specs live under
cypress/component/**/*.cy.tsx
.
See
references/config-and-commands.md
for the directory tree, the complete
cypress.config.ts
, and the
tsconfig.json
additions.

标准布局分为
e2e/
component/
fixtures/
support/
,根目录下的
cypress.config.ts
配置两个运行器。关键配置选项:从环境变量获取
baseUrl
(CI环境中绝不要硬编码)、显式设置视口、CI模式下
retries.runMode: 2
,以及
component.devServer
下的框架/打包工具组合。组件测试用例存放在
cypress/component/**/*.cy.tsx
详见
references/config-and-commands.md
中的目录结构、完整
cypress.config.ts
以及
tsconfig.json
的补充配置。

Custom Commands

自定义命令

Custom commands encapsulate repeated actions behind a clean, typed API. Common commands:
login
(via
cy.session
+ API, not UI), a
getByTestId
selector shorthand, and assertion helpers like
shouldShowToast
. Declare them in
cypress/support/index.d.ts
(
declare namespace Cypress { interface Chainable { ... } }
with JSDoc
@example
) so they get autocomplete and compile-time checking.
cy.session
needs a
validate()
callback.
cy.session
caches cookies/localStorage/sessionStorage automatically, but without
validate()
the cached session is never re-verified -- a stale or expired token silently reuses a dead session. Always pass a
validate()
that hits an authenticated endpoint (e.g.
cy.request('/api/me').its('status').should('eq', 200)
).
Retryable lookups use
Cypress.Commands.addQuery()
, and the callback must be a non-arrow
function () {}
-- Cypress binds
this
to apply the command timeout, so an arrow function silently breaks retry-ability. (Intercept handlers are the opposite:
(req) => {}
is fine there because they do not use
this
.)
See
references/config-and-commands.md
for the full command definitions, the
validate()
callback, the
addQuery
example, and the TypeScript declarations.

自定义命令将重复操作封装为简洁的类型化API。常见命令:
login
(通过
cy.session
+ API实现,而非UI操作)、
getByTestId
选择器简写,以及
shouldShowToast
等断言辅助函数。在
cypress/support/index.d.ts
中声明(
declare namespace Cypress { interface Chainable { ... } }
并添加JSDoc
@example
),以便获得自动补全和编译时检查。
cy.session
需要
validate()
回调。
cy.session
会自动缓存Cookie/localStorage/sessionStorage,但如果没有
validate()
,缓存的会话永远不会被重新验证——过期的令牌会静默复用失效的会话。始终传入
validate()
回调,调用一个需要认证的接口(例如
cy.request('/api/me').its('status').should('eq', 200)
)。
可重试的查找需使用
Cypress.Commands.addQuery()
,且回调必须是非箭头函数
function () {}
——Cypress会绑定
this
以应用命令超时,箭头函数会静默破坏重试机制。(拦截处理器则相反:
(req) => {}
是可行的,因为它们不使用
this
。)
详见
references/config-and-commands.md
中的完整命令定义、
validate()
回调、
addQuery
示例以及TypeScript声明。

cy.intercept Patterns

cy.intercept模式

cy.intercept
covers the full network-control surface:
  • Stub a response — return canned data with
    { statusCode, body }
    , then
    cy.wait('@alias')
    .
  • Spy without stubbing
    cy.intercept('POST', '/api/orders').as('createOrder')
    , then assert on
    interception.request.body
    and
    interception.response?.statusCode
    .
  • Conditional responses — drive a closure with
    callCount
    to simulate polling (202 → 200). The handler arrow function
    (req) => { ... }
    is correct here.
  • Network errors
    { statusCode: 500 }
    ,
    { forceNetworkError: true }
    , or
    req.reply({ delay })
    for slow responses.
  • Modify real responses
    req.continue((res) => { ...; res.send(); })
    .
  • Fixture-backed
    { fixture: 'api-responses/checkout-success.json' }
    .
Register the intercept before the action that triggers the request, or the alias never matches.
See
references/intercept-patterns.md
for runnable code for each, plus cross-origin flows.

cy.intercept
覆盖完整的网络控制场景:
  • 存根响应 —— 使用
    { statusCode, body }
    返回预设数据,然后调用
    cy.wait('@alias')
  • 监听不存根 ——
    cy.intercept('POST', '/api/orders').as('createOrder')
    ,然后断言
    interception.request.body
    interception.response?.statusCode
  • 条件响应 —— 使用
    callCount
    驱动闭包模拟轮询(202 → 200)。此处使用箭头函数
    (req) => { ... }
    作为处理器是正确的。
  • 网络错误 ——
    { statusCode: 500 }
    { forceNetworkError: true }
    req.reply({ delay })
    模拟慢响应。
  • 修改真实响应 ——
    req.continue((res) => { ...; res.send(); })
  • 基于fixture ——
    { fixture: 'api-responses/checkout-success.json' }
请在触发请求的操作之前注册拦截,否则别名永远无法匹配。
详见
references/intercept-patterns.md
中的可运行代码示例,以及跨域流程说明。

Component Testing

组件测试

Component testing mounts a single component in a real browser without running the full app -- faster than E2E, more visual feedback than unit tests. Use
cy.mount(<Component .../>)
, pass
cy.stub()
/
cy.spy()
for callbacks, and assert with the same
cy.contains
/
cy.get
chain you use in E2E. Never use
cy.visit
in a component test. For Vue, use
cy.mount(Component, { props: { ... } })
.
See
references/component-and-fixtures.md
for a full React
ProductCard
component-test suite.

组件测试在真实浏览器中挂载单个组件,无需运行完整应用——比E2E测试更快,比单元测试提供更多视觉反馈。使用
cy.mount(<Component .../>)
,为回调传入
cy.stub()
/
cy.spy()
,并使用与E2E测试相同的
cy.contains
/
cy.get
链式调用进行断言。组件测试中绝不要使用
cy.visit
。对于Vue,使用
cy.mount(Component, { props: { ... } })
详见
references/component-and-fixtures.md
中的完整React
ProductCard
组件测试套件。

Data-Driven Testing with Fixtures

使用Fixtures的数据驱动测试

Three layers, depending on where the data comes from:
  • Static fixtures
    cy.fixture('users').as('users')
    for JSON that rarely changes; read it via
    this.users
    in a
    beforeEach(function () { ... })
    .
  • Dynamic data via
    cy.task
    — register Node-side tasks in
    setupNodeEvents
    for API calls or DB seeding that must run outside the browser (task bodies run in Node, so
    fetch
    there is Node's global fetch, not a Cypress API).
  • Environment-specific config — merge a per-environment
    baseUrl
    map in
    setupNodeEvents
    , selected by
    --env ENVIRONMENT=...
    .
See
references/component-and-fixtures.md
for the fixture,
cy.task
seeding, and env-config code.

分为三层,取决于数据来源:
  • 静态fixtures ——
    cy.fixture('users').as('users')
    用于极少变化的JSON数据;在
    beforeEach(function () { ... })
    中通过
    this.users
    读取。
  • 通过
    cy.task
    获取动态数据
    —— 在
    setupNodeEvents
    中注册Node端任务,用于执行必须在浏览器外运行的API调用或数据库初始化(任务体在Node中运行,因此此处的
    fetch
    是Node的全局fetch,而非Cypress API)。
  • 环境特定配置 —— 在
    setupNodeEvents
    中合并每个环境的
    baseUrl
    映射,通过
    --env ENVIRONMENT=...
    选择。
详见
references/component-and-fixtures.md
中的fixture、
cy.task
初始化以及环境配置代码。

Cross-Origin Flows

跨域流程

For legitimate redirects to another domain (SSO, OAuth providers, a separate auth host), wrap the commands that run on the other origin in
cy.origin
. This replaced the old
chromeWebSecurity: false
/
experimentalSessionAndOrigin
escape hatches -- do not disable web security to work around a redirect. This is distinct from third-party payment iframes (Stripe/PayPal), which you stub with
cy.intercept
and never reach into.
See
references/intercept-patterns.md
(Cross-Origin Flows) for the
cy.origin
example.

对于合法的重定向到其他域名(SSO、OAuth提供商、独立认证主机),将在其他域名上运行的命令包裹在
cy.origin
中。这替代了旧的
chromeWebSecurity: false
/
experimentalSessionAndOrigin
解决方案——不要为了处理重定向而禁用Web安全。注意这与第三方支付iframe(Stripe/PayPal)不同,后者需使用
cy.intercept
存根,绝不要直接操作。
详见
references/intercept-patterns.md
(跨域流程)中的
cy.origin
示例。

CI Integration

CI集成

Action version: pin to
cypress-io/github-action@v7
(latest 7.2.0, May 2026). v7 runs under Node 24 and is the current major; use
@v6
only on a Node 20 runner (the legacy branch).
Cypress / Node support: Current is Cypress 15.x, which supports Node 20, 22, and 24 (Node 18 and 23 dropped). Node 20 removal is a future Cypress 16 / action-v7.2 concern tracking the Node 20 EOL (2026-04-30), not something Cypress 15 did.
  • With Cypress Cloud: set
    projectId
    , run
    npx cypress run --record --key $CYPRESS_RECORD_KEY
    , and parallelize across a container matrix (
    fail-fast: false
    ) for flake detection, Test Replay, and analytics.
  • Without Cloud: use
    cypress-io/github-action@v7
    with
    build
    /
    start
    /
    wait-on
    , and upload
    cypress/screenshots
    +
    cypress/videos
    as artifacts on failure.
See
references/ci-recipes.md
for both complete GitHub Actions workflows.
Cypress AI (paid Cloud add-on, GA 2026) ships Auto Heal (selector self-healing), AI Test Generation, and AI Bug Triage. Now GA and worth knowing:
cy.prompt
(English-to-test authoring with runtime self-healing) and Cloud MCP (GA May 2026, free on all Cloud plans) — an MCP server that feeds recorded-run errors, stack traces, and Test Replay links to your AI assistant. This overlaps
test-reliability
(selector healing),
ai-bug-triage
(failure clustering), and
ai-test-generation
(authoring). If the team is already on Cypress Cloud, buying the add-on may be cheaper than building the equivalent -- flag it during framework selection.

Action版本: 固定为
cypress-io/github-action@v7
(最新版本7.2.0,2026年5月)。v7运行在Node 24环境下,是当前主版本;仅在Node 20运行器上使用
@v6
(旧分支)。
Cypress/Node支持情况: 当前版本为Cypress 15.x,支持Node 20、22和24(已移除Node 18和23)。Node 20的移除是未来Cypress 16/action-v7.2需要关注的问题,跟踪Node 20的EOL(2026-04-30),并非Cypress 15的改动。
  • 使用Cypress Cloud: 设置
    projectId
    ,运行
    npx cypress run --record --key $CYPRESS_RECORD_KEY
    ,并在容器矩阵中并行执行(
    fail-fast: false
    ),以实现不稳定测试检测、Test Replay和分析功能。
  • 不使用Cloud: 使用
    cypress-io/github-action@v7
    ,配置
    build
    /
    start
    /
    wait-on
    ,并在测试失败时上传
    cypress/screenshots
    +
    cypress/videos
    作为产物。
详见
references/ci-recipes.md
中的完整GitHub Actions工作流示例。
Cypress AI(付费Cloud附加功能,2026年GA) 包含Auto Heal(选择器自修复)、AI测试生成和AI Bug分类。现已GA,值得关注:
cy.prompt
(自然语言转测试编写,运行时自修复)和Cloud MCP(2026年5月GA,所有Cloud计划免费)——一个MCP服务器,将录制运行的错误、堆栈跟踪和Test Replay链接提供给AI助手。这与
test-reliability
(选择器修复)、
ai-bug-triage
(失败聚类)和
ai-test-generation
(测试编写)有重叠。如果团队已使用Cypress Cloud,购买该附加功能可能比自行开发更划算——在框架选择阶段需标记此点。

Anti-Patterns

反模式

1. cy.wait(milliseconds) for Synchronization

1. 使用cy.wait(毫秒数)进行同步

typescript
// BAD
cy.get('[data-testid="submit"]').click();
cy.wait(3000);

// GOOD -- wait for network
cy.intercept('POST', '/api/submit').as('submit');
cy.get('[data-testid="submit"]').click();
cy.wait('@submit');
Only acceptable for throttle/debounce testing. Everything else waits on a network alias or a DOM assertion.
typescript
// 错误写法
cy.get('[data-testid="submit"]').click();
cy.wait(3000);

// 正确写法——等待网络请求
cy.intercept('POST', '/api/submit').as('submit');
cy.get('[data-testid="submit"]').click();
cy.wait('@submit');
仅在测试节流/防抖时可接受。其他场景均应等待网络别名或DOM断言。

2. Conditional Testing Based on DOM State

2. 基于DOM状态进行条件测试

Do not check
$body.find(selector).length > 0
to conditionally act. Control state deterministically -- stub the API that drives the conditional element.
不要通过
$body.find(selector).length > 0
来判断是否执行操作。应确定性地控制状态——存根驱动条件元素的API。

3. CSS Selectors Over Data Attributes

3. 使用CSS选择器而非数据属性

cy.get('.btn.btn-primary > span')
breaks on every CSS refactor. Use
cy.getByTestId('submit')
or
cy.contains('button', 'Place Order')
.
cy.get('.btn.btn-primary > span')
会在每次CSS重构时失效。使用
cy.getByTestId('submit')
cy.contains('button', 'Place Order')

4. Sharing State Between Tests

4. 在测试间共享状态

Module-level
let orderId
set in one
it()
and read in another creates order-dependent, parallel-unsafe tests. Each test sets up its own data via
cy.request
or
cy.task
in
beforeEach
.
在一个
it()
中设置模块级变量
let orderId
并在另一个
it()
中读取,会导致测试依赖执行顺序且无法并行运行。每个测试应通过
beforeEach
中的
cy.request
cy.task
自行设置数据。

5. Testing Third-Party Iframes

5. 测试第三方iframe

Do not reach into Stripe/PayPal iframes. Mock the payment API with
cy.intercept
and assert on your own UI.
不要直接操作Stripe/PayPal的iframe。使用
cy.intercept
模拟支付API,并断言自身UI。

6. Not Using cy.session() for Login (or Omitting validate())

6. 不使用cy.session()进行登录(或省略validate())

UI login in every test is slow and fragile. Use
cy.session
to authenticate via API once and cache it -- with a
validate()
callback so an expired token does not silently reuse a dead session.
每个测试都通过UI登录既慢又脆弱。使用
cy.session
通过API认证一次并缓存会话——务必添加
validate()
回调,避免过期令牌静默复用失效会话。

7. Arrow Function in addQuery

7. 在addQuery中使用箭头函数

A custom query written with
addQuery('name', (arg) => { ... })
silently loses its retry timeout because Cypress needs
this
. Use
function (arg) { ... }
.
使用
addQuery('name', (arg) => { ... })
编写的自定义查询会静默丢失超时重试机制,因为Cypress需要
this
。请使用
function (arg) { ... }

8. Running All Tests Serially in CI

8. 在CI中串行运行所有测试

Parallelize once the suite exceeds 5 minutes -- Cypress Cloud,
cypress-split
, or manual sharding across a CI matrix.

当测试套件执行时间超过5分钟时,应并行执行——可使用Cypress Cloud、
cypress-split
或在CI矩阵中手动分片。

Failure Modes

故障模式

SymptomLikely causeFix
element is detached from the DOM
A yielded element was reused after a re-renderRe-query inside
.should
/
.then
instead of holding the old reference
cy.intercept
did not match / alias never resolves
Wrong method or glob, or intercept registered after the actionRegister the intercept before the triggering command; verify method + URL glob
cross origin
error on redirect
Login or flow crosses to another domainWrap the other-origin commands in
cy.origin
; do not disable
chromeWebSecurity
Session reused but user is logged out
cy.session
has no
validate()
, token expired
Add a
validate()
callback that hits an authenticated endpoint
Custom query never times out / retries forever
addQuery
callback is an arrow function
Convert to
function () {}
so Cypress can bind
this

症状可能原因修复方案
element is detached from the DOM
渲染后复用了之前获取的元素
.should
/
.then
中重新查询,而非保留旧引用
cy.intercept
未匹配 / 别名永远无法解析
请求方法或URL匹配错误,或拦截在操作后注册在触发命令前注册拦截;验证请求方法+URL匹配规则
重定向时出现
cross origin
错误
登录或流程跨域将跨域命令包裹在
cy.origin
中;不要禁用
chromeWebSecurity
会话被复用但用户已登出
cy.session
没有
validate()
,令牌过期
添加调用认证接口的
validate()
回调
自定义查询永不超时 / 无限重试
addQuery
回调是箭头函数
转换为
function () {}
,以便Cypress绑定
this

Verification

验证

Prove the suite runs before calling it done:
  • npx cypress verify
    — confirms the Cypress binary is installed and runnable.
  • npx cypress run --spec "cypress/e2e/<file>.cy.ts"
    — should exit 0 (headless, in CI mode).
  • npx cypress run --component --spec "cypress/component/<File>.cy.tsx"
    — component specs exit 0.
  • npx tsc --noEmit
    — custom-command declarations in
    index.d.ts
    compile against the test files.

完成前需验证套件可正常运行:
  • npx cypress verify
    —— 确认Cypress二进制文件已安装且可运行。
  • npx cypress run --spec "cypress/e2e/<file>.cy.ts"
    —— 应返回0(无头模式,CI模式)。
  • npx cypress run --component --spec "cypress/component/<File>.cy.tsx"
    —— 组件测试用例应返回0。
  • npx tsc --noEmit
    ——
    index.d.ts
    中的自定义命令声明应能与测试文件编译通过。

Done When

完成标准

  • cypress.config.ts
    exists with a
    baseUrl
    from env (not hardcoded
    localhost
    in CI) and explicit
    viewportWidth
    /
    viewportHeight
    ;
    npx cypress verify
    passes.
  • Custom commands extracted to
    cypress/support/commands.ts
    with TypeScript declarations in
    cypress/support/index.d.ts
    ;
    npx tsc --noEmit
    exits 0.
  • The
    login
    command uses
    cy.session
    with a
    validate()
    callback.
  • No
    cy.wait(<number>)
    for synchronization in the suite (
    grep -rn "cy.wait([0-9]" cypress/
    returns nothing except documented throttle/debounce cases).
  • Component specs live under
    cypress/component/**/*.cy.tsx
    and run with
    npx cypress run --component
    exiting 0.
  • E2E specs pass in CI (
    npx cypress run
    exits 0) with either a recorded Cypress Cloud run (parallel) or local video/screenshot artifacts uploaded on failure.
  • 存在
    cypress.config.ts
    ,从环境变量获取
    baseUrl
    (CI环境中不硬编码
    localhost
    ),并显式设置
    viewportWidth
    /
    viewportHeight
    npx cypress verify
    通过。
  • 自定义命令提取到
    cypress/support/commands.ts
    ,并在
    cypress/support/index.d.ts
    中添加TypeScript声明;
    npx tsc --noEmit
    返回0。
  • login
    命令使用带
    validate()
    回调的
    cy.session
  • 套件中无用于同步的
    cy.wait(<数字>)
    grep -rn "cy.wait([0-9]" cypress/
    无结果,除非是文档说明的节流/防抖测试场景)。
  • 组件测试用例存放在
    cypress/component/**/*.cy.tsx
    ,且
    npx cypress run --component
    返回0。
  • E2E测试用例在CI中通过(
    npx cypress run
    返回0),要么记录到Cypress Cloud(并行执行),要么在失败时上传本地视频/截图产物。

Reference Files (in
references/
)

参考文件(位于
references/

  • config-and-commands.md — Project directory tree, full
    cypress.config.ts
    , and custom commands (
    cy.session
    +
    validate()
    , the non-arrow
    addQuery
    ) with TypeScript declarations.
  • intercept-patterns.md — Every
    cy.intercept
    recipe (stub, spy, conditional/polling, error simulation, response modification, fixture-backed) plus cross-origin flows with
    cy.origin
    .
  • component-and-fixtures.md — React component-test suite plus data-driven testing (static fixtures,
    cy.task
    seeding, env-specific config).
  • ci-recipes.md — GitHub Actions workflows with and without Cypress Cloud, on
    @v7
    , with parallelization and artifact upload.
  • config-and-commands.md —— 项目目录结构、完整
    cypress.config.ts
    、自定义命令(带
    validate()
    cy.session
    、非箭头函数的
    addQuery
    )以及TypeScript声明。
  • intercept-patterns.md —— 所有
    cy.intercept
    示例(存根、监听、条件/轮询、错误模拟、响应修改、基于fixture),以及基于
    cy.origin
    的跨域流程。
  • component-and-fixtures.md —— React组件测试套件,以及数据驱动测试(静态fixtures、
    cy.task
    初始化、环境特定配置)。
  • ci-recipes.md —— 使用和不使用Cypress Cloud的GitHub Actions工作流,基于
    @v7
    ,包含并行执行和产物上传。

Related Skills

相关技能

  • playwright-automation — Use instead of this skill when the suite is Playwright, not Cypress. Same E2E goals, different runner and API.
  • test-reliability — Go here for runtime per-test flake healing, self-healing locators, and quarantine. This skill writes stable tests; that one repairs failing ones.
  • selector-drift-recovery — Bulk-regenerate broken selectors after a UI refactor or redesign; this skill is for authoring, not mass repair.
  • test-migration — Converting Selenium/other suites to Cypress.
  • ci-cd-integration — Pipeline templates for running Cypress in GitHub Actions / GitLab CI, parallelization, and artifact management.
  • visual-testing — Visual regression to complement Cypress functional tests; Cypress has no built-in pixel comparison.
  • unit-testing — Jest/Vitest for logic that needs no browser; Cypress component tests fill the gap between unit and E2E.
  • test-data-management — Seeding, managing, and cleaning up the test data Cypress tests consume.
  • qa-project-context — The project context file capturing framework choices, CI platform, and conventions.
  • playwright-automation —— 当测试套件为Playwright而非Cypress时,使用该技能。目标相同,但运行器和API不同。
  • test-reliability —— 用于运行时单测不稳定修复、自修复定位器和隔离。本技能用于编写稳定测试;该技能用于修复失败测试。
  • selector-drift-recovery —— UI重构或重新设计后批量重新生成失效选择器;本技能用于编写测试,而非批量修复。
  • test-migration —— 将Selenium/其他套件迁移到Cypress。
  • ci-cd-integration —— 在GitHub Actions/GitLab CI中运行Cypress的流水线模板、并行执行和产物管理。
  • visual-testing —— 视觉回归测试,补充Cypress功能测试;Cypress无内置像素对比功能。
  • unit-testing —— 使用Jest/Vitest测试无需浏览器的逻辑;Cypress组件测试填补了单元测试与E2E测试之间的空白。
  • test-data-management —— 初始化、管理和清理Cypress测试使用的测试数据。
  • qa-project-context —— 记录框架选择、CI平台和约定的项目上下文文件。