系统学习 测试与质量四阶段学习路径:从单元与接口测试,到端到端、性能、契约和 CI 门禁

Cypress 的 retry-ability、网络拦截、跨域登录与 CI 配置

适用场景

前端团队希望测试与开发服务器一起跑,调试时能在浏览器里逐步回放每个命令,适合中小型 Web 应用的端到端与组件测试。Cypress 在浏览器内执行,天然适合同源页面和前端路由;需要多标签页、跨域跳转或更完整的多浏览器矩阵时,应评估 Playwright。

核心概念 / 语法

常用示例

安装并验证:

npm install -D cypress
npx cypress verify
npx cypress open

最小配置 cypress.config.ts:

import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    baseUrl: 'http://127.0.0.1:3000',
    specPattern: 'cypress/e2e/**/*.cy.ts',
    retries: { runMode: 2, openMode: 0 },
    video: true,
    screenshotOnRunFailure: true,
    setupNodeEvents(on, config) {
      return config;
    },
  },
});

登录用例与 retry-ability:

describe('登录', () => {
  it('登录后进入工作台', () => {
    cy.visit('/login');
    cy.get('[data-cy=email]').type('qa@example.com');
    cy.get('[data-cy=password]').type('test-password');
    cy.get('[data-cy=submit]').click();

    cy.location('pathname').should('eq', '/dashboard');
    cy.contains('h1', '工作台').should('be.visible');
    cy.get('[data-cy=order-row]').should('have.length', 3);
  });
});

should('have.length', 3) 会持续重试,直到行数变成 3 或超时;不要写成 cy.wait(2000) 再断言。

拦截登录接口并校验请求:

cy.intercept('POST', '/api/login').as('login');

cy.visit('/login');
cy.get('[data-cy=email]').type('qa@example.com');
cy.get('[data-cy=password]').type('test-password');
cy.get('[data-cy=submit]').click();

cy.wait('@login').then(({ request, response }) => {
  expect(request.body).to.include({ email: 'qa@example.com' });
  expect(response?.statusCode).to.eq(200);
});
cy.location('pathname').should('eq', '/dashboard');

需要固定后端返回时,把 cy.intercept 的第二个参数换成 { statusCode: 200, body: { ... } },但关键路径仍应保留真实接口测试。

CI 中启动应用并运行 Cypress:

npm ci
npm run build
npm run start &
npx wait-on http://127.0.0.1:3000
npx cypress run --browser chrome
# 需要并行时改用 Cypress Cloud 项目与 record key
npx cypress run --record --parallel --key "$CYPRESS_RECORD_KEY"

失败时 Cypress 会把截图写入 cypress/screenshots、录像写入 cypress/videos,CI 应把这两个目录作为失败产物上传。只在本机加 --parallel 不会生效,必须有 --record 和云端项目。

易错点

相关条目

参考链接

读完自测

  1. 为什么不能在 Cypress 测试里用 async/await 去接 cy.get() 的返回值?
  2. cy.intercept 应该放在什么位置,cy.wait('@login') 在什么情况下会一直等到超时?
  3. 在 CI 上开启 Cypress 并行执行需要哪些条件?
答案
  1. Cypress 命令是排入队列的 Chainable 而不是 Promise,await 拿不到元素,异步函数还可能让命令在测试结束后才执行;应使用 .then() 或链式断言。
  2. 必须在触发请求之前注册,并保证 URL 和 method 能匹配;如果请求没有发出、被缓存或匹配规则写错,cy.wait 就会超时。
  3. 需要 Cypress Cloud 项目、CYPRESS_RECORD_KEY、--record 和 --parallel;仅在本机加 --parallel 不会生效。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令