Cypress E2E 测试
约 230 字小于 1 分钟
布欧-Lewyon
2026-05-15
安装
npm install -D cypress
npx cypress open配置
// cypress.config.ts
import { defineConfig } from 'cypress'
export default defineConfig({
e2e: {
baseUrl: 'http://localhost:5173',
supportFile: 'cypress/support/e2e.ts',
},
})基本测试
// cypress/e2e/todo.cy.ts
describe('Todo App', () => {
beforeEach(() => {
cy.visit('/')
})
it('should display the title', () => {
cy.contains('Todo App').should('be.visible')
})
it('should add a new todo', () => {
cy.get('[data-testid="todo-input"]').type('Learn Cypress')
cy.get('[data-testid="add-button"]').click()
cy.contains('Learn Cypress').should('be.visible')
})
it('should toggle a todo', () => {
cy.get('[data-testid="todo-item"]').first().click()
cy.get('[data-testid="todo-item"]').first()
.should('have.class', 'completed')
})
})网络请求拦截
it('loads users from API', () => {
cy.intercept('GET', '/api/users', {
fixture: 'users.json', // 模拟返回
}).as('getUsers')
cy.visit('/users')
cy.wait('@getUsers')
cy.get('[data-testid="user-item"]')
.should('have.length', 3)
.first()
.should('contain', 'Alice')
})小结
- Cypress 是 E2E 测试标准工具,
cy.visit()cy.get()cy.contains()。 cy.intercept()拦截和模拟 API 响应。data-testid属性避免测试与 CSS class 耦合。- E2E 测试核心用户流程(登录 → 操作 → 校验)。
