Cypress 端到端测试实战:从安装到 CI 集成
Sarah Wong | 2026-08-27T20:54:42 | JavaScript, Frontend
手把手教你用 Cypress 编写 E2E 测试用例,涵盖登录流程、API mock、自定义命令和 GitHub Actions 集成。
# Cypress 端到端测试实战 ## 安装与初始化 ```bash npm install -D cypress npx cypress open ``` Cypress 会自动生成项目结构: ``` cypress/ e2e/ -- 测试用例 fixtures/ -- 测试数据 support/ -- 自定义命令和全局配置 ``` ## 第一个测试:登录流程 ```javascript // cypress/e2e/login.cy.js describe('登录功能', () => { beforeEach(() => { cy.visit('/login'); }); it('应该成功登录并跳转到首页', () => { cy.get('[data-testid="email-input"]').type('admin@example.com'); cy.get('[data-testid="password-input"]').type('password123'); cy.get('[data-testid="login-button"]').click(); // 断言跳转到首页 cy.url().should('include', '/dashboard'); cy.get('[data-testid="welcome-text"]').should('contain', '欢迎'); }); it('密码错误应显示错误提示', () => { cy.get('[data-testid="email-input"]').type('admin@example.com'); cy.get('[data-testid="password-input"]').type('wrong'); cy.get('[data-testid="login-button"]').click(); cy.get('[data-testid="error-message"]') .should('be.visible') .and('contain', '密码错误'); }); }); ``` ## 自定义命令 ```javascript // cypress/support/commands.js Cypress.Commands.add('login', (email, password) => { cy.session([email, password], () => { cy.request('POST', '/api/auth/login', { email: email, password: password, }).then((resp) => { window.localStorage.setItem('token', resp.body.token); }); }); }); // 在测试中使用 beforeEach(() => { cy.login('admin@example.com', 'password123'); cy.visit('/dashboard'); }); ``` ## API Mock(拦截网络请求) ```javascript it('应该展示文章列表', () => { cy.intercept('GET', '/api/posts*', { fixture: 'posts.json', }).as('getPosts'); cy.visit('/posts'); cy.wait('@getPosts'); cy.get('[data-testid="post-card"]').should('have.length', 10); }); ``` ## 配置文件 ```javascript // cypress.config.js const { defineConfig } = require('cypress'); module.exports = defineConfig({ e2e: { baseUrl: 'http://localhost:3000', viewportWidth: 1280, viewportHeight: 720, video: false, screenshotOnRunFailure: true, retries: { runMode: 2, openMode: 0, }, }, }); ``` ## GitHub Actions 集成 ```yaml # .github/workflows/e2e.yml name: E2E Tests on: [push, pull_request] jobs: cypress: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cypress-io/github-action@v6 with: build: npm run build start: npm start wait-on: 'http://localhost:3000' browser: chrome ``` ## 最佳实践 1. 使用 `data-testid` 属性定位元素,避免依赖 CSS 类名 2. 每个测试用例保持独立,不依赖前一个测试的状态 3. API 请求用 `cy.intercept` mock,保证测试稳定性 4. CI 环境关闭视频录制以加快速度