Cypress E2E 前端自动化测试

FreeGuideOnline 14阅读 2026-07-09

提交

```javascript
cy.get('[data-cy=submit-btn]').click()

运行与调试

命令行运行(CI 常用)

npx cypress run                # 默认 Electron 无头运行
npx cypress run --browser chrome  # 指定浏览器
npx cypress run --spec "cypress/e2e/login.cy.js"  # 运行单个文件

可视化调试

使用 cypress open 进入图形化 Test Runner,可查看时间旅行快照、每一步前后的 DOM 状态、控制台输出。通过 .debug()cy.pause() 可在特定步骤暂停执行。

截图与录屏

失败用例自动截图保存在 cypress/screenshots,视频保存在 cypress/videos。可在配置中关闭视频录制或设置 videoUploadOnPasses: false

配置文件详解

cypress.config.js 常见配置:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',     // 默认地址前缀
    specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}',
    supportFile: 'cypress/support/e2e.js',
    viewportWidth: 1280,
    viewportHeight: 720,
    defaultCommandTimeout: 10000,
    pageLoadTimeout: 60000,
    retries: {
      runMode: 2,    // 命令行运行失败重试次数
      openMode: 0    // 可视化模式
    },
    env: {
      apiUrl: 'https://staging-api.example.com'
    }
  }
})

测试中通过 Cypress.env('apiUrl') 读取自定义环境变量。

常见测试场景示例

登录流程测试

it('使用有效凭据登录', () => {
  cy.visit('/login')
  cy.get('[data-cy=email]').type('[email protected]')
  cy.get('[data-cy=password]').type('password123')
  cy.get('[data-cy=login-btn]').click()
  cy.url().should('include', '/dashboard')
  cy.contains('Welcome back').should('be.visible')
})

文件上传测试

it('上传头像', () => {
  cy.get('input[type="file"]').selectFile('cypress/fixtures/avatar.png', { force: true })
  cy.get('.upload-success').should('contain', '上传成功')
})

拖拽测试

需使用 @4tw/cypress-drag-drop 插件,或使用原生触发:

it('拖拽排序', () => {
  const dataTransfer = new DataTransfer()
  cy.get('#item-1').trigger('dragstart', { dataTransfer })
  cy.get('#item-3').trigger('drop', { dataTransfer })
  cy.get('.list > li').eq(0).should('contain', 'Item 2')
})

与 CI/CD 集成

Cypress 提供官方 Docker 镜像,可快速在流水线中执行。以 GitHub Actions 为例:

- name: Run Cypress tests
  uses: cypress-io/github-action@v5
  with:
    start: npm start
    wait-on: 'http://localhost:3000'
    browser: chrome