Cypress 15
Cypress 15 的安装方式和之前版本基本一致,核心变化主要在运行环境要求和Studio 能力升级上。下面是一份从零到一的实操教程。
环境要求(Cypress 15 新增)
Cypress 15 对 Node.js 版本有明确要求:仅支持 Node.js 22.x、24.x 或 ≥26.x,已移除对 Node 18 和 23 的支持。
先检查当前版本:
node -v
npm -v如果版本不满足,建议用 nvm 切换:
nvm install 22
nvm use 22安装步骤
1. 初始化项目
mkdir cypress-demo && cd cypress-demo
npm init -y2. 安装 Cypress
npm install cypress --save-dev强烈建议本地安装而非全局安装,这样可以锁定版本,保证团队和 CI 环境一致。
3. 验证安装
npx cypress verify4. 首次启动
npx cypress open首次运行会自动生成 cypress/ 目录结构和 cypress.config.js 配置文件。
目录结构
cypress/
├── e2e/ # 端到端测试用例(.cy.js / .cy.ts)
├── fixtures/ # 静态测试数据(JSON 等)
├── support/
│ ├── commands.js # 自定义命令
│ └── e2e.js # 全局前置配置
└── downloads/ # 测试中下载的文件
cypress.config.js # 核心配置文件基础配置
在项目根目录的 cypress.config.js 中:
const { defineConfig } = require('cypress')
module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:3000', // 本地开发服务器地址
specPattern: 'cypress/e2e/**/*.cy.{js,ts}', // 测试文件匹配
supportFile: 'cypress/support/e2e.js',
viewportWidth: 1280,
viewportHeight: 720,
video: false, // 本地调试可关闭
screenshotOnRunFailure: true,
retries: {
runMode: 2, // CI 模式失败重试 2 次
openMode: 0, // 交互模式不重试,方便调试
},
experimentalStudio: true, // 开启 Cypress 15 Studio
setupNodeEvents(on, config) {
// 插件注册位置
},
},
})设置 baseUrl 是最佳实践——之后用 cy.visit('/login') 即可,切换环境时只需改一处。
第一个测试用例
在 cypress/e2e/login.cy.js 中:
describe('用户登录', () => {
it('正确账号应登录成功', () => {
cy.visit('/login')
cy.get('[data-cy=username]').type('admin')
cy.get('[data-cy=password]').type('123456')
cy.get('[data-cy=submit]').click()
cy.url().should('include', '/dashboard')
cy.contains('欢迎回来').should('be.visible')
})
})运行方式
- 图形界面(调试用):
npx cypress open— 可视化执行,支持时间旅行 - 无头模式(CI 用):
npx cypress run— 自动录制视频,失败时截图
Cypress 15 值得关注的变化
- Cypress Studio 升级: 支持在浏览器中点击录制测试、右键添加断言、内联编辑测试代码,是 AI 辅助测试生成的基础。
- Command Log 视觉重构: 按 SESSIONS / BEFORE EACH / TEST BODY 分层分组,调试时更易定位。
- 底层改进:
cy.url()、cy.go()改用自动化协议,跨源场景更稳定;新增 Vite 7 和 Angular 20 支持。 - 弃用项: 移除 Node 18/23、Webpack 4、Vite 4、Angular 17 以及 Firefox CDP 模式支持。
常用 npm scripts
在 package.json 中添加:
{
"scripts": {
"cypress:open": "cypress open",
"cypress:run": "cypress run",
"cypress:run:chrome": "cypress run --browser chrome"
}
}之后用 npm run cypress:open 或 npm run cypress:run 即可。