开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情
Cypress 提供了两种测试类型,e2e 测试和 component 测试,在本文中,主要针对 e2e 测试,component 测试暂时没有涉猎。
前期准备
- 参考上一篇,Cypress 成功安装,基础代码(需要手敲)
- 或者直接
clone
git clone https://gitee.com/yuestone-info/cypress-test.git -b juejin.cn/post/7173831711896109069
Cypress 自动配置 e2e
在通过 npm run dev 启动 Cypress 应用之后,如果没有检测到任何配置,那么我们点击 E2E Testing 之后,将会自动增加许多信息
暂未配置
如果项目是全新的,则首先会弹出该页面,以引导用户开始使用Cypress
配置文件一览
进来之后,Cypress 会自动配置一些文件和文件夹,以方便进行测试
截止目前,项目文件夹已经增加了一些配置文件,文件目录树如下:
|-- node_modules
|-- cypress // [新增] 主要目录,cypress 所有文件基本的写在这里
|--|-- fixtures // [新增] 测试夹具。Mock / 静态数据
|--|--|-- example.json // [新增] 示例文件
|--|-- support // [新增] 可重用配置项。底层通用函数 / 全局默认配置
|--|--|-- commands.js // [新增] 通用命令定义,比如 login
|--|--|-- e2e.js // [新增] 在运行测试用例前自动加载
|-- cypress.config.js // [新增] 配置信息
|-- package.json
|-- package-lock.json
配置成功
Continue,目前的浏览器有:默认的Chrome,Electron。Edge(Win10 自带) 和 Firefox 则需要电脑上提前安装。
正常调试一般推荐 Chrome,可以看到 URL 地址栏等信息
在 Chrome 中开始 E2E 测试
进来之后,整体的布局结构是分左右两边,左边是 Specs、Runs 和 Settings,右边则分别是其内容部分
因为我们暂时没有 Specs,根据引导,我们可以使用示例的specs,也可以选择空的 spec。此处我们先选择 example specs。
使用示例测试
Cypress 默认内置了 todo 的一些测试用例,我们在开发的过程中,也可以借鉴和参考。
每一个 xx.cy.js 都可以单独运行。
截止目前为止,文件目录树应该如下:
|-- node_modules
|-- cypress
|--|-- e2e // [新增] 相比之前,新增了 e2e 文件夹
|--|--|-- 1-getting-started // [新增] 示例数据 1
|--|--|-- |-- todo.cy.js // [新增] 示例数据 1 下的测试用例
|--|--|-- 2-advanced-examples // [新增] 示例数据 1
|--|--|-- |-- actions.cy.js // [新增] 示例数据 2 下的测试用例 actions
|--|--|-- |-- ... // [新增] 示例数据 2 下其他的测试用例
|--|-- fixtures
|--|--|-- example.json
|--|-- support
|--|--|-- commands.js
|--|--|-- e2e.js
|-- cypress.config.js
|-- package.json
|-- package-lock.json
运行 todo.cy.js
todo.cy.js 运行如下:
了解部分文件(夹)
cypress.config.js 文件
Cypress 应用会通过该配置文件,进行配置测试内容。我们展开其中内容后,再仔细理解一下。
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
});
可以看到,默认的配置是非常简洁的,这是因为 cypress 内置了很多的默认参数,当然,我们完全可以按照自己的心意进行配置。
Global
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
clientCertificates | [] | |
env | {} | 环境变量 |
includeShadowDom | false | 遍历 shadow DOM |
numTestsKeptInMemory | 50 | 内存中存在的测试数量 |
port | null | Cypress 的端口,默认是随机生成的 |
redirectionLimit | 20 | 被测应用程序在出错前可以重定向的次数。 |
reporter | spec | 报告样式 |
reporterOptions | null | 报告的一些配置 |
retries | { "runMode": 0, "openMode": 0 } | 重试次数,可以配置 run 和 open 模式 |
watchForFileChanges | true | 文件修改后,实时反馈到 Cypress |
Timeouts
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
defaultCommandTimeout | 4000 | 默认命令超时时间,单位 ms |
execTimeout | 60000 | cy.exec() 超时时间 |
taskTimeout | 60000 | cy.task() 超时时间 |
pageLoadTimeout | 60000 | 页面加载超时时间 |
requestTimeout | 5000 | request 超时时间 |
responseTimeout | 30000 | response 超时时间 |
Folders / Files
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
downloadsFolder | cypress/downloads | 文件下载目录 |
fileServerFolder | root project folder | |
fixturesFolder | cypress/fixtures | 夹具文件夹,设置为 false 禁用 |
screenshotsFolder | cypress/screenshots | 截图保存目录 |
videosFolder | cypress/videos | 视频保存目录 |
Screenshots
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
screenshotOnRunFailure | true | cypress run 的时候,失败的测试用例截图 |
screenshotsFolder | cypress/screenshots | 截图保存目录 |
trashAssetsBeforeRuns | true | cypress run 的时候,删除资源 |
Videos
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
trashAssetsBeforeRuns | true | cypress run 的时候,删除资源 |
videoCompression | 32 | 0-51,视频压缩质量 |
videosFolder | cypress/videos | 视频保存目录 |
video | true | cypress run 的时候,录制视频 |
videoUploadOnPasses | true | 用例失败的时候,自动上传视频到 Cypress Cloud |
Downloads
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
downloadsFolder | cypress/downloads | 下载目录 |
trashAssetsBeforeRuns | true | cypress run 的时候,删除资源 |
Browser
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
chromeWebSecurity | true | 安全策略 |
blockHosts | null | 主机黑名单 |
modifyObstructiveCode | true | |
userAgent | null | 设置 userAgent |
Viewport
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
viewportHeight | 660 | 默认高度 |
viewportWidth | 1000 | 默认宽度 |
Actionability
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
animationDistanceThreshold | 5 | |
waitForAnimations | true | 是否等待动画完成 |
scrollBehavior | top |
e2e
e2e下 官方配置如下,可根据喜好进行配置,此处简单介绍一下配置
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
baseUrl | null | cy.visit()或者cy.request的前缀 |
setupNodeEvents | null | node相关的一些事件或者配置在此处可以做些处理 |
supportFile | cypress/support/e2e.{js,jsx,ts,tsx} | 支持性文件,在spec加载之前编译。设置为 false 可以禁用 |
specPattern | cypress/e2e/**/*.cy.{js,jsx,ts,tsx} | 可以使用 String / Array 配置要探测的测试文件。可以动态设置该属性,可选的运行测试用例 |
excludeSpecPattern | *.hot-update.js | 可以使用 String / Array 配置要排除探测的测试文件。可以动态设置该属性,可选的运行测试用例 |
experimentalSessionAndOrigin | false | |
slowTestThreshold | 10000 | |
testIsolation | null | |
experimentalRunAllSpecs | false |
component
| 配置项 | 默认值 | 描述/意义 |
|---|---|---|
devServer | null | |
setupNodeEvents | null | |
supportFile | cypress/support/component.js | |
specPattern | **/*.cy.{js,jsx,ts,tsx} | |
excludeSpecPattern | ['/snapshots/*', '/image_snapshots/*'] | |
experimentalSingleTabRunMode | false | |
slowTestThreshold | 250 |
fixtures 文件夹
该文件夹下的内容主要是一些静态文件或者静态数据,例如需要固定的测试数据或者需要上传的文件等
定义:fixtures/example.json
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}
使用:example.json
cy.fixture('example').then(function(user) {
cy.log(user)
})
support 文件夹
该文件夹下内容,主要有两个,一个是 commands.js 和 e2e.js。
commands.js
该文件主要用于自定义命令,比较通用的一些,例如 login 等命令
// 定义
Cypress.Commands.add('login', (username, password) => {
...
})
// 使用,在任意 *.cy.js 文件中
cy.login('username', 'password')
e2e.js
该文件主要在运行测试文件前,自动加载运行
// Import commands.js using ES2015 syntax:
import './commands'
// Alternatively you can use CommonJS syntax:
// require('./commands')
// 例如:可以在这里写钩子
beforeEach(function(){
cy.log(`当前环境变量为: ${JSON.stringify(Cypress.env())}`)
cy.log(`当前配置项信息为: ${JSON.stringify(Cypress.config())}`)
})
e2e 文件夹
该文件夹下所有的 *.cy.js 文件都会被识别为测试文件,所以,我们的所有测试文件和测试用例都在此处编写
// *.cy.js
describe('测试Demo', () => {
before(() => {
cy.login()
cy.log('登录成功,运行一次,做一些准备工作')
})
it('第一个', () => {
...
})
it('第二个', () => {
...
})
after(() => {
cy.logout()
cy.log('注销登录,运行一次,做一些清理工作')
})
})
videos 文件夹
录制的视频保存文件夹
screenshots 文件夹
截图的文件保存文件
Cypress Command Line
cypress run [options]
配置项
| 配置项 | 描述/意义 |
|---|---|
--browser, -b | 配置浏览器 |
--ci-build-id | |
--component | 运行 componet 测试 |
--config, -c | 指定配置 |
--config-file, -C | 指定配置文件 |
--e2e | 运行 e2e 测试 |
--env, -e | 指定环境变量 |
--group | |
--headed | 显示浏览器 |
--headless | 隐藏浏览器 |
--help, -h | 输出帮助信息 |
--key, -k | 指定 Cloud Project 的 key |
--no-exit | 运行结束不退出 |
--parallel | 并行 |
--port,-p | 指定端口 |
--project, -P | 指定项目 |
--quiet, -q | 默认不输出日志 |
--record | 记录运行 |
--reporter, -r | 指定报告 |
--reporter-options, -o | 指定报告配置 |
--spec, -s | 指定测试用例 |
--tag, -t | 使用 tag 运行 |
通用的几个命令
# 指定浏览器运行, 浏览器可选:chrome, chromium, edge, electron, firefox
cypress run --browser chrome
# 指定配置运行
cypress run --config pageLoadTimeout=100000,watchForFileChanges=false
# 指定配置文件运行,此处可以配置多环境
cypress run --config-file tests/cypress.config.js
# 指定环境变量
cypress run --env host=api.dev.local,port=4222
# 将测试结果记录到 Cloud 上
cypress run --record --key <record_key>
cypress open [options]
配置项
| 配置项 | 描述/意义 |
|---|---|
--browser, -b | 配置浏览器 |
--component | 运行 componet 测试 |
--config, -c | 指定配置 |
--config-file, -C | 指定配置文件 |
--detached,-d | 分离模式 |
--e2e | 运行 e2e 测试 |
--env, -e | 指定环境变量 |
--global | 全局模式 |
--help,-h | 输出帮助信息 |
--port,-p | 指定端口 |
--project,-P | 指定项目路径 |
通用的几个命令
# 指定浏览器
cypress open --browser /usr/bin/chromium
# 指定配置
cypress open --config "{\"watchForFileChanges\":false,\"specPattern\":[\"**/*.cy.js\",\"**/*.cy.ts\"]}"
# 指定配置文件
cypress open --config-file tests/cypress.config.js
# 指定环境变量
cypress open --env flags='{"feature-a":true,"feature-b":false}'
# 指定项目
cypress open --project ./some/nested/folder
cypress info
Displaying Cypress info...
Detected 1 browser installed:
1. Chrome
- Name: chrome
- Channel: stable
- Version: 107.0.5304.121
- Executable: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
- Profile: /Users/zhen/Library/Application Support/Cypress/cy/production/browsers/chrome-stable
Note: to run these browsers, pass <name>:<channel> to the '--browser' field
Examples:
- cypress run --browser chrome
Learn More: https://on.cypress.io/launching-browsers
Proxy Settings: none detected
Environment Variables: none detected
Application Data: /Users/zhen/Library/Application Support/cypress/cy/development
Browser Profiles: /Users/zhen/Library/Application Support/cypress/cy/development/browsers
Binary Caches: /Users/zhen/Library/Caches/Cypress
Cypress Version: 10.11.0 (stable)
System Platform: darwin (22.1.0)
System Memory: 17.2 GB free 753 MB
cypress version
Cypress package version: 10.11.0
Cypress binary version: 10.11.0
Electron version: 21.0.0
Bundled Node version: 16.16.0
cypress verify
✔ Verified Cypress! /Users/xxx/Library/Caches/Cypress/10.11.0/Cypress.app
cypress cache [command]
Enable Debug Logs
DEBUG=cypress:* cypress open
代码地址
git clone https://gitee.com/yuestone-info/cypress-test.git -b juejin.cn/post/7174388888920195085