Cypress 安装与配置 #
系统要求 #
操作系统 #
| 操作系统 | 支持版本 |
|---|---|
| macOS | 10.15+ |
| Windows | Windows 10+ |
| Linux | Ubuntu 18.04+, CentOS 7+, Debian 9+ |
Node.js 版本 #
bash
# 检查 Node.js 版本
node -v
# 推荐 Node.js 18.x 或更高版本
# 最低支持 Node.js 14.x
浏览器支持 #
| 浏览器 | 支持情况 |
|---|---|
| Chrome | ✅ 完全支持 |
| Chromium | ✅ 完全支持 |
| Edge | ✅ 完全支持 |
| Electron | ✅ 内置支持 |
| Firefox | ✅ 支持 |
| Safari | ⚠️ 实验性支持 |
安装 Cypress #
方式一:npm 安装(推荐) #
bash
# 创建项目目录
mkdir my-cypress-project
cd my-cypress-project
# 初始化 npm 项目
npm init -y
# 安装 Cypress
npm install cypress --save-dev
方式二:yarn 安装 #
bash
# 初始化项目
yarn init -y
# 安装 Cypress
yarn add cypress --dev
方式三:pnpm 安装 #
bash
# 初始化项目
pnpm init
# 安装 Cypress
pnpm add cypress --save-dev
验证安装 #
bash
# 检查 Cypress 版本
npx cypress --version
# 输出示例
# Cypress package version: 13.6.0
# Cypress binary version: 13.6.0
# Electron version: 25.0.0
# Bundled Node version: 18.15.0
初始化项目 #
打开 Cypress #
bash
# 打开 Cypress Test Runner
npx cypress open
首次运行会自动创建项目结构:
text
my-project/
├── cypress/
│ ├── e2e/ # E2E 测试目录
│ │ ├── 1-getting-started/
│ │ │ └── todo.cy.js # 示例测试
│ │ └── 2-advanced-examples/
│ │ └── actions.cy.js # 高级示例
│ ├── fixtures/ # 测试数据
│ │ └── example.json
│ ├── support/ # 支持文件
│ │ ├── commands.js # 自定义命令
│ │ └── e2e.js # 配置文件
│ └── screenshots/ # 截图目录(自动创建)
├── cypress.config.js # 配置文件
└── package.json
添加 npm 脚本 #
json
// package.json
{
"scripts": {
"cy:open": "cypress open",
"cy:run": "cypress run",
"cy:run:chrome": "cypress run --browser chrome",
"cy:run:headless": "cypress run --headless"
}
}
配置文件 #
cypress.config.js 基本配置 #
javascript
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
viewportWidth: 1280,
viewportHeight: 720,
defaultCommandTimeout: 4000,
pageLoadTimeout: 60000,
responseTimeout: 30000,
video: true,
screenshotOnRunFailure: true,
}
});
完整配置选项 #
javascript
const { defineConfig } = require('cypress');
module.exports = defineConfig({
// 全局配置
viewportWidth: 1280,
viewportHeight: 720,
viewportPreserve: false,
// 超时配置
defaultCommandTimeout: 4000,
pageLoadTimeout: 60000,
responseTimeout: 30000,
requestTimeout: 5000,
execTimeout: 60000,
taskTimeout: 60000,
// 视频和截图
video: true,
videoCompression: 32,
videosFolder: 'cypress/videos',
screenshotOnRunFailure: true,
screenshotsFolder: 'cypress/screenshots',
// 文件监听
watchForFileChanges: true,
// 测试文件
specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}',
excludeSpecPattern: ['*.page.js'],
// 浏览器
chromeWebSecurity: true,
blockHosts: ['*.google-analytics.com'],
// E2E 特定配置
e2e: {
baseUrl: 'http://localhost:3000',
supportFile: 'cypress/support/e2e.js',
setupNodeEvents(on, config) {
// 插件配置
on('task', {
log(message) {
console.log(message);
return null;
}
});
}
},
// 组件测试配置
component: {
devServer: {
framework: 'react',
bundler: 'webpack'
},
specPattern: 'src/**/*.cy.{js,jsx,ts,tsx}',
supportFile: 'cypress/support/component.js'
}
});
TypeScript 配置 #
bash
# 安装 TypeScript
npm install typescript --save-dev
json
// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM"],
"types": ["cypress", "node"],
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"cypress/**/*.ts",
"cypress.config.ts"
]
}
typescript
// cypress.config.ts
import { defineConfig } from 'cypress';
export default defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
setupNodeEvents(on, config) {
// 配置插件
}
}
});
环境变量 #
配置文件中设置 #
javascript
// cypress.config.js
module.exports = defineConfig({
e2e: {
env: {
apiUrl: 'https://api.example.com',
adminUser: 'admin@example.com',
adminPassword: 'password123'
}
}
});
命令行传递 #
bash
# 单个环境变量
npx cypress run --env apiUrl=https://staging-api.example.com
# 多个环境变量
npx cypress run --env apiUrl=https://staging-api.example.com,mode=staging
环境文件 #
text
cypress/
├── config/
│ ├── development.json
│ ├── staging.json
│ └── production.json
json
// cypress/config/staging.json
{
"baseUrl": "https://staging.example.com",
"env": {
"apiUrl": "https://staging-api.example.com"
}
}
javascript
// cypress.config.js
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
const env = config.env.environment || 'development';
const configPath = `./cypress/config/${env}.json`;
const envConfig = require(configPath);
return { ...config, ...envConfig };
}
}
});
使用环境变量 #
javascript
// 在测试中使用
cy.visit(Cypress.env('apiUrl'));
cy.get('#email').type(Cypress.env('adminUser'));
测试文件组织 #
推荐目录结构 #
text
cypress/
├── e2e/
│ ├── auth/ # 认证相关测试
│ │ ├── login.cy.js
│ │ ├── register.cy.js
│ │ └── password-reset.cy.js
│ ├── dashboard/ # 仪表盘测试
│ │ └── overview.cy.js
│ ├── products/ # 产品相关测试
│ │ ├── list.cy.js
│ │ └── detail.cy.js
│ └── checkout/ # 结账流程测试
│ └── payment.cy.js
├── fixtures/ # 测试数据
│ ├── users/
│ │ ├── admin.json
│ │ └── customer.json
│ └── products/
│ └── sample.json
├── support/ # 支持文件
│ ├── commands/ # 自定义命令
│ │ ├── auth.js
│ │ └── api.js
│ ├── pages/ # 页面对象
│ │ ├── LoginPage.js
│ │ └── DashboardPage.js
│ ├── utils/ # 工具函数
│ │ └── helpers.js
│ └── e2e.js # 入口文件
└── plugins/ # 插件
└── index.js
支持文件配置 #
javascript
// cypress/support/e2e.js
// 导入自定义命令
import './commands/auth';
import './commands/api';
// 导入插件
import 'cypress-file-upload';
import '@testing-library/cypress/add-commands';
// 全局配置
before(() => {
// 全局前置操作
});
afterEach(() => {
// 每个测试后清理
cy.clearCookies();
cy.clearLocalStorage();
});
浏览器配置 #
指定浏览器运行 #
bash
# Chrome
npx cypress run --browser chrome
# Firefox
npx cypress run --browser firefox
# Edge
npx cypress run --browser edge
# Electron(默认)
npx cypress run --browser electron
# 指定浏览器路径
npx cypress run --browser /path/to/browser
浏览器启动选项 #
javascript
// cypress.config.js
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('before:browser:launch', (browser, launchOptions) => {
if (browser.family === 'chromium') {
launchOptions.args.push('--disable-web-security');
launchOptions.args.push('--disable-site-isolation-trials');
}
if (browser.name === 'chrome') {
launchOptions.args.push('--window-size=1920,1080');
}
return launchOptions;
});
}
}
});
CI/CD 配置 #
GitHub Actions #
yaml
# .github/workflows/cypress.yml
name: Cypress Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
cypress:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run Cypress tests
uses: cypress-io/github-action@v6
with:
browser: chrome
start: npm start
wait-on: 'http://localhost:3000'
- name: Upload screenshots
uses: actions/upload-artifact@v4
if: failure()
with:
name: cypress-screenshots
path: cypress/screenshots
GitLab CI #
yaml
# .gitlab-ci.yml
cypress:
image: cypress/browsers:node-20-chrome
stage: test
script:
- npm ci
- npm start &
- npx wait-on http://localhost:3000
- npx cypress run --browser chrome
artifacts:
when: on_failure
paths:
- cypress/screenshots
- cypress/videos
expire_in: 1 week
CircleCI #
yaml
# .circleci/config.yml
version: 2.1
orbs:
cypress: cypress-io/cypress@3
workflows:
build:
jobs:
- cypress/run:
cypress-command: npx cypress run --browser chrome
start-command: npm start
wait-on: 'http://localhost:3000'
常用插件安装 #
文件上传插件 #
bash
npm install --save-dev cypress-file-upload
javascript
// cypress/support/e2e.js
import 'cypress-file-upload';
测试库插件 #
bash
npm install --save-dev @testing-library/cypress
javascript
// cypress/support/e2e.js
import '@testing-library/cypress/add-commands';
视觉测试插件 #
bash
npm install --save-dev cypress-image-snapshot
真实事件插件 #
bash
npm install --save-dev cypress-real-events
配置最佳实践 #
1. 分环境配置 #
javascript
// cypress.config.js
const { defineConfig } = require('cypress');
const envConfig = {
development: {
baseUrl: 'http://localhost:3000',
video: false
},
staging: {
baseUrl: 'https://staging.example.com',
video: true
},
production: {
baseUrl: 'https://example.com',
video: true
}
};
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
const env = config.env.environment || 'development';
return { ...config, ...envConfig[env] };
}
}
});
2. 敏感信息管理 #
bash
# 使用 .env 文件(不要提交到版本控制)
# .env
CYPRESS_ADMIN_PASSWORD=secret123
CYPRESS_API_KEY=abc123xyz
javascript
// 在测试中使用
cy.get('#password').type(Cypress.env('ADMIN_PASSWORD'));
3. 性能优化配置 #
javascript
module.exports = defineConfig({
e2e: {
// 减少视频大小
videoCompression: 32,
// 禁用不必要的功能
video: false,
screenshotOnRunFailure: false,
// 减少超时时间
defaultCommandTimeout: 3000,
pageLoadTimeout: 30000,
// 并行执行
numTestsKeptInMemory: 5
}
});
常见问题解决 #
1. 安装失败 #
bash
# 清除缓存重新安装
npx cypress cache clear
npm install cypress --save-dev
2. 浏览器找不到 #
bash
# 查看可用浏览器
npx cypress info
# 手动指定浏览器路径
CYPRESS_BROWSER_PATH=/path/to/browser npx cypress run
3. 权限问题 #
bash
# macOS/Linux
sudo chown -R $(whoami) ~/.cache/Cypress
下一步 #
现在你已经完成了 Cypress 的安装和配置,接下来学习 基础测试编写 开始编写你的第一个测试!
最后更新:2026-03-28