从零开始完整安装 Cypress 的终极指南

从零开始完整安装 Cypress 的终极指南

以下是 从零开始完整安装 Cypress 的终极指南,包含从环境检查到验证安装的全流程:

完整安装流程图

1. 检查 Node.js 和 npm 环境

node -v # 查看当前版本,我的v18.20.8

npm -v # 查看当前版本,我的v10.8.2

版本低? :过低会导致cypress某些函数不可用;

-

版本高? :过高会导致无法安装cypress;

2. 创建项目目录(如未存在)

项目目录结构

my-cypress-project/

├── cypress/

│ ├── e2e/ # 测试用例,文件命名在主配置文件中保持一致

│ │ ├── test.cy.js # test测试示例

│ │ └── order.cy.js # 下单流程测试

│ │ └── ...... # 自定义测试

│ ├── fixtures/ # 测试数据

│ │ ├── parameter.json # 自定义参数

│ ├── support/ # 支持文件,文件命名在主配置文件中保持一致

│ │ ├── commands.js # 自定义命令、函数

│ │ └── e2e.js # 测试支持文件

│ ├── downloads/ # 下载文件(可选)

│ ├── screenshots/ # 失败截图(可选)

│ ├── videos/ # 测试录像(可选)

│ └── config/ # 环境配置(可选)

│ │ ├── dev.json

│ │ └── test.json

│ │ └── prod.json

├── cypress.config.js # 主配置文件

├── package.json # 项目依赖,无需创建,初始化则出现

└── tsconfig.json # TypeScript配置(如使用TS)

文件引用关系图

创建目录:Windows CMD 专用命令

:: 创建项目文件夹

mkdir my-cypress-project

cd my-cypress-project

:: 初始化项目,生成package.json

npm init -y

创建目录:macOS/Linux 专用命令(没验证过)

# 创建项目文件夹

mkdir -p my-cypress-project/cypress/{e2e,fixtures,support,config,downloads,screenshots,videos}

cd my-cypress-project

# 初始化项目

npm init -y

3. 安装 Cypress

标准安装

npm install cypress --save-dev

锁定版本安装(推荐)

npm install cypress@12.17.4 --save-dev

安装成功验证

安装成功后会自动生成一下两个目录

my-cypress-project/

├── node_modules/

├── package-lock.json

查看cypress版本

cypress -v

检查缓存目录

Windows:

%APPDATA%\Local\Cypress\Cache\12.17.4\CypressmacOS/Linux:

~/.cache/Cypress/13.6.0/Cypress

4. 初始化 Cypress 项目

npx cypress open # 首次运行会生成目录结构

正常会根据你的选择自动生成的核心文件结构,若不自动生成则需要手工创建:

自动创建目录

cypress/

├── e2e/ # 测试用例

├── fixtures/ # 测试数据

├── support/ # 支持文件

├── downloads/ # 下载文件

└── videos/ # 测试录像

手工创建目录:Windows CMD 专用命令

cd my-cypress-project

:: 生成目录结构

mkdir cypress

mkdir cypress\e2e

mkdir cypress\fixtures

mkdir cypress\support

mkdir cypress\config

mkdir cypress\downloads

mkdir cypress\screenshots

mkdir cypress\videos

:: 创建核心文件

type nul > cypress.config.js

type nul > cypress\e2e\test.cy.js

type nul > cypress\e2e\order.cy.js

type nul > cypress\fixtures\parameter.json

type nul > cypress\support\commands.js

type nul > cypress\support\e2e.js

type nul > cypress\config\dev.json

type nul > cypress\config\test.json

type nul > cypress\config\prod.json

手工创建目录:macOS/Linux 专用命令(没验证过)

# 创建项目文件夹

mkdir -p cypress/{e2e,fixtures,support,config,downloads,screenshots,videos}

cd my-cypress-project

# 生成核心文件

touch cypress.config.js \

cypress/e2e/test.cy.js \

cypress/e2e/order.cy.js \

cypress/fixtures/parameter.json \

cypress/support/commands.js \

cypress/support/e2e.js \

cypress/config/{dev.json,test.json,prod.json}

5. 基础配置

① package.json - 依赖与脚本

{

"name": "my-cypress-project",

"version": "1.0.0",

"scripts": {

"cy:open": "cypress open",

"cy:run": "cypress run --browser Google Chrome",

"cy:run:ci": "cypress run --record --key your-record-key",

"test:e2e": "start-server-and-test start http://localhost:3000 cy:run",

"lint": "eslint cypress/"

},

"dependencies": {

"react": "^18.0.0",

"vue": "^3.0.0"

},

"devDependencies": {

"cypress": "^13.0.0",

"@cypress/react": "^5.0.0",

"@cypress/webpack-dev-server": "^2.0.0",

"eslint-plugin-cypress": "^2.0.0",

"start-server-and-test": "^1.0.0"

},

"engines": {

"node": ">=16.14.0 <=20.x",

"npm": ">=8.0.0"

},

"volta": {

"node": "18.20.8",

"npm": "10.8.2"

}

}

② cypress.config.js - 主配置文件

const { defineConfig } = require('cypress')

const fs = require('fs') //加载Node.js 核心模块 File System

// 动态加载环境变量

const loadEnv = (env = 'dev') => {

return JSON.parse(fs.readFileSync(`./cypress/config/${env}.json`))

}

module.exports = defineConfig({

// 测试超时设置

defaultCommandTimeout: 10000,

pageLoadTimeout: 60000,

// E2E 测试配置

e2e: {

// baseUrl: 'https://your-app.com',

specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}',

supportFile: 'cypress/support/e2e.js',

// 插件配置

setupNodeEvents(on, config) {

// 同步读取文件内容,并以UTF-8编码返回文件内容封装成 cy.task('readFile', 'filename')

on('task', {

readFile(filename) {

return fs.readFileSync(filename, 'utf8')

}

})

// 动态合并环境变量

config.env = { ...config.env, ...loadEnv(process.env.ENV) }

return config

}

},

// 浏览器,默认会生成你系统的文件,我的谷歌没正常带出,就自己写了

browsers: [

{

name: 'edge',

family: 'chromium',

channel: 'stable',

displayName: 'Edge',

version: '137.0.3296.83',

path: 'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe',

majorVersion: '137',

},

{

name: 'Google Chrome',

family: 'chromium',

channel: 'dev',

displayName: 'Google',

version: '137.0.7117.2',

path: 'C:\\Users\\xhtx\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe',

majorVersion: '137',

},

{

name: 'electron',

channel: 'stable',

family: 'chromium',

displayName: 'Electron',

version: '130.0.6723.137',

path: '',

majorVersion: 130,

},

],

// 组件测试配置(需安装 @cypress/react/vue)

/*component: {

devServer: {

framework: 'react',

bundler: 'webpack'

}

},*/

// 截图/录像配置

screenshotsFolder: 'cypress/screenshots',

trashAssetsBeforeRuns: true, // 每次运行前清理旧文件

video: true,

videoCompression: 32

})

③ cypress/support/e2e.js - 支持文件

// 全局beforeEach钩子

beforeEach(() => {

cy.log(`Running test: ${Cypress.currentTest.title}`)

})

/* 这段代码定义了一个新的断言方法approx,用于检查一个值是否在某个期望值的误差范围内。这个方法接受两个参数:

expected:期望的值。

margin:允许的误差范围,默认值为0.1。

如果实际值与期望值的差值在误差范围内,断言通过;否则,断言失败。*/

chai.Assertion.addMethod('approx', function (expected, margin = 0.1) {

const actual = this._obj

this.assert(

Math.abs(expected - actual) <= margin,

`expected #{this} to be approximately #{exp} (±${margin})`,

`expected #{this} not to be approximately #{exp} (±${margin})`,

expected

)

})

// 导入自定义命令

import './commands'

// 导入自定义命令

import './commands'

④ cypress/support/commands.js - 自定义命令

// 登录快捷命令

Cypress.Commands.add('login', (url, name, password) => {

cy.log(`Logging in to ${url} with username ${name}`);

cy.visit(url);

cy.get('input[name="username"]').type(name);

cy.get('input[name="password"]').type(password);

cy.get('#fm1 > input.btn.btn-block.btn-submit.col-lg-6.col-xl-6.col-md-8.col-sm-8.offset-xl-3.offset-lg-3.offset-md-2.offset-sm-2').click();

});

⑤ cypress/fixtures/users.json - 测试数据

{

"admin": {

"email": "admin@test.com",

"role": "administrator",

"permissions": ["read", "write", "delete"]

},

"guest": {

"email": "guest@test.com",

"role": "viewer"

}

}

⑥ cypress/config/dev.json - 环境变量

{

"url": "https://******.com/cas/login",

"name": "134******31",

"password": "******"

}

环境变量优先级

cypress.config.js 中的 env 对象cypress/config/[env].json 文件命令行参数:npx cypress run --env API_URL=https://custom.com

6. 运行测试

开发模式(交互式)

npm run cy:open

命令行模式(CI/CD)

npm run cy:run

开发工具

什么工具都行,我用的idea,open自己的项目

简单测试用例

cypress/e2e/login.cy.js - 简单测试用例

import param from '../fixtures/example.json'; //引入参数,此处没用到

describe('Login Test', () => {

it('试着调用函数', () => {

cy.login(Cypress.env('url'), Cypress.env('name'), Cypress.env('password'));

});

});

cypress语法

问问AI

7. 常见问题解决方案

问题 1:安装卡在 Downloading Cypress

# 方案1:手动下载后指定路径

export CYPRESS_INSTALL_BINARY="/path/to/cypress.zip"

npm install cypress

# 方案2:使用代理

export HTTP_PROXY=http://your-proxy:port

export HTTPS_PROXY=http://your-proxy:port

问题 2:权限错误

# Linux/macOS

sudo chown -R $(whoami) ~/.cache/Cypress

# Windows

以管理员身份运行终端

问题 3:版本冲突

# 彻底清理后重装

rm -rf node_modules package-lock.json

npm cache clean --force

npm install

8.版本兼容性参考表

Node.js 版本Cypress 兼容版本npm 要求v16.x10.x - 13.x≥8v18.x12.x - 最新版≥8v20.x13.x+≥9

相关推荐

发蜡可以定型吗
365账号投注被限制

发蜡可以定型吗

📅 07-26 👁️ 3080
这样“打”猫才能让它越来越乖,还不让它受伤
365账号投注被限制

这样“打”猫才能让它越来越乖,还不让它受伤

📅 06-29 👁️ 4327
代表月亮的字
365bet官网注册

代表月亮的字

📅 08-05 👁️ 514