Cypress 初识

649 阅读8分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情

Cypress 提供了两种测试类型,e2e 测试和 component 测试,在本文中,主要针对 e2e 测试,component 测试暂时没有涉猎。

前期准备

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{}环境变量
includeShadowDomfalse遍历 shadow DOM
numTestsKeptInMemory50内存中存在的测试数量
portnullCypress 的端口,默认是随机生成的
redirectionLimit20被测应用程序在出错前可以重定向的次数。
reporterspec报告样式
reporterOptionsnull报告的一些配置
retries{ "runMode": 0, "openMode": 0 }重试次数,可以配置 run 和 open 模式
watchForFileChangestrue文件修改后,实时反馈到 Cypress

Timeouts

配置项默认值描述/意义
defaultCommandTimeout4000默认命令超时时间,单位 ms
execTimeout60000cy.exec() 超时时间
taskTimeout60000cy.task() 超时时间
pageLoadTimeout60000页面加载超时时间
requestTimeout5000request 超时时间
responseTimeout30000response 超时时间

Folders / Files

配置项默认值描述/意义
downloadsFoldercypress/downloads文件下载目录
fileServerFolderroot project folder
fixturesFoldercypress/fixtures夹具文件夹,设置为 false 禁用
screenshotsFoldercypress/screenshots截图保存目录
videosFoldercypress/videos视频保存目录

Screenshots

配置项默认值描述/意义
screenshotOnRunFailuretruecypress run 的时候,失败的测试用例截图
screenshotsFoldercypress/screenshots截图保存目录
trashAssetsBeforeRunstruecypress run 的时候,删除资源

Videos

配置项默认值描述/意义
trashAssetsBeforeRunstruecypress run 的时候,删除资源
videoCompression320-51,视频压缩质量
videosFoldercypress/videos视频保存目录
videotruecypress run 的时候,录制视频
videoUploadOnPassestrue用例失败的时候,自动上传视频到 Cypress Cloud

Downloads

配置项默认值描述/意义
downloadsFoldercypress/downloads下载目录
trashAssetsBeforeRunstruecypress run 的时候,删除资源

Browser

配置项默认值描述/意义
chromeWebSecuritytrue安全策略
blockHostsnull主机黑名单
modifyObstructiveCodetrue
userAgentnull设置 userAgent

Viewport

配置项默认值描述/意义
viewportHeight660默认高度
viewportWidth1000默认宽度

Actionability

配置项默认值描述/意义
animationDistanceThreshold5
waitForAnimationstrue是否等待动画完成
scrollBehaviortop

e2e

e2e下 官方配置如下,可根据喜好进行配置,此处简单介绍一下配置

配置项默认值描述/意义
baseUrlnullcy.visit()或者cy.request的前缀
setupNodeEventsnullnode相关的一些事件或者配置在此处可以做些处理
supportFilecypress/support/e2e.{js,jsx,ts,tsx}支持性文件,在spec加载之前编译。设置为 false 可以禁用
specPatterncypress/e2e/**/*.cy.{js,jsx,ts,tsx}可以使用 String / Array 配置要探测的测试文件。可以动态设置该属性,可选的运行测试用例
excludeSpecPattern*.hot-update.js可以使用 String / Array 配置要排除探测的测试文件。可以动态设置该属性,可选的运行测试用例
experimentalSessionAndOriginfalse
slowTestThreshold10000
testIsolationnull
experimentalRunAllSpecsfalse

component

配置项默认值描述/意义
devServernull
setupNodeEventsnull
supportFilecypress/support/component.js
specPattern**/*.cy.{js,jsx,ts,tsx}
excludeSpecPattern['/snapshots/*', '/image_snapshots/*']
experimentalSingleTabRunModefalse
slowTestThreshold250

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.jse2e.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