Cypress的安装和配置方法
一、安装 Cypress
1. 项目初始化(如果尚未初始化)
bash 运行npm init -y
2. 安装 Cypress(推荐本地安装)
bash 运行npm install cypress --save-dev
为什么选择本地安装?
确保团队成员使用相同版本的 Cypress,避免环境差异导致的问题。
3. 安装后结构
安装完成后,Cypress 会在项目根目录生成以下结构:
plaintext 运行cypress/├── e2e/ # 测试用例文件夹├── support/ # 支持文件(如命令、配置)├── fixtures/ # 测试数据└── plugins/ # 插件配置cypress.config.js # 主配置文件
二、配置 Cypress
1. 启动配置向导
bash 运行npx cypress open
首次启动时,Cypress 会自动创建默认配置文件和示例测试。
2. 主配置文件(cypress.config.js)
可自定义以下核心配置:
javascript 运行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, // 命令超时时间(毫秒)},});
3. 环境变量配置
在 cypress.config.js 中添加 env 字段:
javascript 运行module.exports = defineConfig({e2e: {env: {API\_URL: 'https://api.example.com',USERNAME: 'testuser',PASSWORD: 'testpass',},// ...其他配置},});
在测试中通过 Cypress.env() 访问:
javascript 运行cy.request(\`${Cypress.env('API\_URL')}/users\`);
三、自定义测试环境
1. 多环境配置
创建 cypress.env.json 文件:
json 运行{"development": {"API\_URL": "http://dev-api.example.com"},"production": {"API\_URL": "https://api.example.com"}}
运行时指定环境:
bash 运行npx cypress open --env environment=development
2. 浏览器配置
在 cypress.config.js 中设置默认浏览器:
javascript 运行module.exports = defineConfig({e2e: {browser: 'chrome', // 可选: chrome, edge, firefox 等// ...},});
四、支持 TypeScript
1. 安装依赖
bash 运行npm install typescript @types/cypress --save-dev
2. 创建 tsconfig.json
json 运行{"compilerOptions": {"target": "ESNext","lib": \["ESNext", "DOM"\],"types": \["cypress"\]},"include": \["cypress/\*\*/\*.ts"\]}
3. 使用 .ts 扩展名编写测试
typescript 运行/// <reference types="cypress" />describe('TypeScript Test', () => {it('should work with TS', () => {cy.visit('/');cy.get('button').should('be.visible');});});
五、配置持续集成(CI)
1. GitHub Actions 示例
创建 .github/workflows/cypress.yml:
yaml 运行name: Cypress Testson: [push]jobs:cypress-run:runs-on: ubuntu-lateststeps:- name: Checkoutuses: actions/checkout@v4- name: Install Node.jsuses: actions/setup-node@v4with:node-version: 18- name: Install dependenciesrun: npm ci- name: Start server and run Cypress testsrun: |npm start &npx cypress run
六、常见问题与解决方案
1. 安装缓慢或失败
使用淘宝镜像:
bash 运行npm install cypress --save-dev --registry=https://registry.npmmirror.com
测试超时
增加 defaultCommandTimeout 配置:
javascript 运行// cypress.config.jsdefaultCommandTimeout: 15000,
跨域请求问题
使用 cy.intercept() 拦截并处理请求:
javascript 运行cy.intercept('GET', '/api/data', { fixture: 'data.json' });
七、验证安装
启动 Cypress:
bash 运行npx cypress open
在测试运行器中,点击 example.cy.js 示例测试。
- 若测试成功运行,说明 Cypress 已正确安装和配置。