Cypress
2022-05-11 21:54:09 15 举报
AI智能生成
Cypress
作者其他创作
大纲/内容
cypress环境搭建
cypress是一个跨平台的桌面应用,支持mac/linux/windows系统
搭建步骤:
1、安装Node.js
安装教程:https://www.runoob.com/nodejs/nodejs-install-setup.html
Node.js 安装包及源码下载地址为:https://nodejs.org/en/download/
2、使用npm命令安装cypress
举个例子:新建任意一个目录,init初始化,然后安装cypress
D:
cd Cypress_projects
mkdir cypress_project01
cd cypress_project01
npm init -y
npm install cypress --save-dev
3、修改package.json文件
找到scripts元素,增加`"cypress": "cypress open"`
{
"scripts": {
"cypress": "cypress open"
}
}
4、启动cypress
npm run cypress:open
npm run cypress
建议使用VsCode打开编辑cypress项目
cypress文件结构
cypress
fixtures
example.json
integration
examples
在此创建测试用例的文件夹
plugins
index.js
support
- commands.js
- index.js
文件结构的详细说明
fixture 测试夹
主要作用
主要用于存储测试用例的外部静态数据
测试夹具的静态数据通常存储在 .json 文件中,如自动生成的 examples.json
静态数据通常是某个网络请求对应的响应部分,包括HTTP状态码和返回值,一般是复制过来更改而不是自己手工填写
使用的好处
消除了对外部功能模块的依赖
已编写的测试用例可以使用测试夹具**提供的固定返回值**,并且你确切知道这个返回值是你想要的
因为无须真正地发送网络请求,所以测试更快
integration 测试文件
所有在 integration 文件下,且文件格式是以下的文件都将被 Cypress 识别为测试文件:
- .js
- .jsx
- .coffee
- .cjsx
plugins
前言:
Cypress 独有优点就是测试代码运行在浏览器之内,使得Cypress 跟其他的测试框架相比,有显著的架构优势,这优点虽然提供了可靠性测试,但也使得和在浏览器之外进行通信更加困难
【痛点:和外部通信困难】
cypress可以在plugins下自定义自己的插件
插件默认位于plugins下的index.js里面,每个测试文件运行之前,Cypres 都会自动加载插件文件 cypress/plugins/index.js
support
每个测试文件运行之前,Cypress都会自动加载支持文件cypress/support/index.js
support目录主要放置可重用配置项,如通用函数和全局默认配置
cypress配置
配置的默认值
cypress的配置文件为cypress.json
cypress.json默认为空
常见的默认值:
Global
链接:https://docs.cypress.io/guides/references/configuration.html#Global
baseUrl:系统主域名
null
env:环境变量
{}
numTestKeptInMemory:保存在内存中的测试用例个数
50
reporter:测试报告的格式
spec
rporterOptions:相应报告格式的配置参数
null
port:cypress占用的端口,默认为随机生成的
null
retries:测试失败重试次数
{ "runMode": 0, "openMode": 0 }
watchForFileChanges:是否监控测试文件的变更并重新测试
true
Timeouts
defaultCommandTimeout:命令默认超时时间
4000
execTimeout:cy.exec() 等待系统命令完成执行的超时时间
60000
taskTimeout:cy.task() 等待任务完成执行的超时时间
60000
pageLoadTimeout:等待页面加载超时时间
60000
requestTimeout:请求发出的超时时间
5000
responseTimeout:响应超时时间
30000
Folders/Files
testFiles:要加载的测试文件,可以指定具体文件,也可以模糊匹配
**/*.*
fileServerFolder:项目根目录
fixturesFolder、integrationFolder、pluginsFile、supportFile:分别表示测试夹、用例文件夹、插件文件夹、支持文件夹
screenshotsFolder:由测试失败或由cy.screenshot()命令引发的截图的默认文件夹
cypress/screenshots
screenShots
screenshotOnRunFailure:运行失败是否截图保存
true
trashAssetsBeforeRuns:运行前丢弃screenshotsFolder 和 videosFolder的内容
true
Viewport
viewportHeight:测试窗口的默认高度
660px
viewportWidth:测试窗口的默认宽度
1000px
重写配置Overriding Options
方式1:命令行
例子:cypress open --config pageLoadTimeout=30000,baseUrl=https://myapp.com
注意:设定多个配置时,以空格分隔开
对于复杂的配置,可以使用单引号包起来的json格式对象来设置
例子:
cypress open --config '{"watchForFileChanges":false,"testFiles":["**/*.js","**/*.ts"]}'
方式2:使用插件文件pluginsFile
方式3:export 环境变量
例子:export CYPRESS_VIEWPORT_WIDTH=800
注意:
1、环境变量的key都是以CYPRESS_作为前缀
2、环境变量的key会被自动规范化,右边的两种方式都是有效的:
1、export CYPRESS_pageLoadTimeout=100000
2、export CYPRESS_PAGE_LOAD_TIMEOUT=100000
3、环境变量的key跟cypress配置的key不匹配的话,将会当成Cypress.env()的一个常规变量来处理
Environment variables that do not match configuration keys will instead be set as regular environment variables for use in your tests with Cypress.env().
方式4:Cypress.config()
Cypress.config('pageLoadTimeout', 100000)
方式5:Test Configuration
cypress可以将具体的配置只应用到某个测试套件suite或者测试用例test中
例子:1、应用到suite中
子主题 1
例子:2、应用到single test中
子主题 1
查看Test Configuration支持的configuration:https://docs.cypress.io/guides/references/configuration.html#Test-Configuration
cypress解析配置的顺序
Default value
默认值
The configuration file
cypress.json
The Cypress environment file
cypress.env.json
这个配置文件需要自己创建,将会被cypress自动识别,这个文件会覆盖cypress.json的一些值
System environment variables
系统环境变量
Command Line arguments
命令行参数
Plugin file
插件文件
cypress编写和组织测试用例
基本的结构
cypress采用了mocha(https://mochajs.org/)的bdd的语法,可以完美适用于集成测试和单元测试,主要通过右边组件来编写和组装测试用例:
describe()
测试套件,可以嵌套,套件至少包含一个测试用例
context()
跟describe()的作用相同
it()
一条测试用例,specify()的作用跟it()的作用相同
before()
beforeEach()
afterEach()
after()
.only()
.skip()
举个例子:
子主题 1
断言方式
Cypress 的断言基于 Chai 断言库,并且增加了对 Sinon-Chai、Chai-jQuery 断言库的支持,其中就包括 BDD 和 TDD 格式的断言。
https://docs.cypress.io/guides/references/assertions.html#Chai
Chai断言库
BDD断言(expect/should)
常见的Chainer
not.equal
expect(name).to.not.equal('Jane')
deep.equal
expect(obj).to.deep.equal({ name: 'Jane' })
be.a
expect('test').to.be.a('string')
include
expect([1,2,3]).to.include(2)
exist
expect(myVar).to.exist
lessThan(value)
expect(5).to.be.lessThan(10)
TDD断言
常见的Chainer
.equal(actual, expected, [message])
assert.equal(3, 3, 'vals equal')
.isNumber(value, [message])
assert.isNumber(2, 'val is number')
Chai-jQuery断言库
常见的Chainer
have.attr
have.css
have.css('background-color', 'rgb(0, 0, 0)')
have.id
have.id('foo')
have.text
have.text('I love testing')
contain
contain('text')
be.visible / be.hidden
常用断言:.should()
语法格式:
.should(chainers)
.should(chainers, value)
.should(chainers, method, value)
.should(callbackFn)
注意:Chainer可以来自 Chai or Chai-jQuery or Sinon-Chai.
常见断言
长度断言
cy.get('li.selected').should('have.length',3)
类断言
cy.get('form').find('input').should('not.hava.class','disabled')
值断言
cy.get('textarea').should('have.value','poloyy')
文本内容
cy.get('a').parent('span.help').should('not.contain','click me')
元素是否可见
cy.get('button').should('be.visible')
元素是否存在
cy.get('#loading').should('not.exist')
元素状态
cy.get(':radio').should('be.checked')
针对css
cy.get('.completed').should('have.css','text-decoration','line-through')
cypress元素定位
id选择器
cy.get("#main1").click()
class选择器
cy.get(".btn").click()
属性选择器
cy.get("button[id='main2']").click()
nth-child(n)选择器
cy.get("ul>li:nth-child(2)").click()
cypress常用命令Command
should
创建一个断言,会不断重试知道用例通过或者超时
and
是.should的别名
as
创建别名供以后使用
语法格式:
as()
使用@来调用,可在cy.get()或者cy.wait()中调用
例子:
给Dom元素起别名
it('disables on click', () => {
cy.get('button[type=submit]').as('submitBtn')
cy.get('@submitBtn').click().should('be.disabled')
})
给route起别名
cy.route('PUT', 'users', 'fx:user').as('userPut')
cy.get('form').submit()
cy.wait('@userPut')
.its('url').should('contain', 'users')
给cy.fixture()的数据起别名
cy.fixture('users-admins.json').as('admins')
check
选中元素,checkbox or radio.
例子:
cy.get('[type="checkbox"]').check() // Check checkbox element
cy.get('[type="radio"]').first().check() // Check first radio element
children
获取Dom子元素的集合
例子:cy.get('nav').children()
clear
清除input或者textarea文本区域的值
clearCookie
清除特定浏览器cookie
clearCookies
清除所有cookie
contains
获取包含特定文本的第一个Dom元素
例子:
cy.get('.nav').contains('About')
cy.contains('Hello')
dblclick
双击元素
debug
设置一个debugger,并打印前一个命令生成返回的内容
例子:cy.get('nav').debug()
first/last
获取第一个(最后一个)Dom元素
例子:cy.get('nav a').first()
fixture
加载位于文件中的一组固定数据
语法格式:
cy.fixture(filePath)
文件路径
cy.fixture(filePath, encoding)
encoding是读取文件使用的编码
cy.fixture(filePath, options)
cy.fixture(filePath, encoding, options)
例子:
加载一个json文件的数据
cy.fixture('users.json').as('usersData')
加载一张图片
cy.fixture('logo.png').then((logo) => {
// 加载 logo.png
})
加载文件不指定后缀时,解析顺序是:
json->js->coffee->html->
txt->csv->png->jpg->jpeg->....
get
通过选择器selector来获取Dom元素
invoke
获取上一条命令的返回结果并执行调用方法
语法格式:
.invoke(functionName)
.invoke(options, functionName)
options指的是log,timeout等
.invoke(functionName, args...)
args是传递给函数的参数,无数量限制
.invoke(options, functionName, args...)
例子:cy.get('.modal').invoke('show')
trigger
触发一个Dom元素的事件
例子
cy.get('button').trigger('mouseover')
鼠标停在元素上方
cy.get('.target').trigger('mousedown')
cy.wait(1000)
cy.get('.target').trigger('mouseleave')
鼠标长点击
parent
then
task
子主题 1
within
visit
wait
cy.wait(time)
等待多少毫秒
cy.wait(alias)
子主题 1
request
wrap
返回(生成)传递给它的对象
例子:
// 声明一个整数 cy.wrap(123).should('eq', 123)
// 声明一个字符串 cy.wrap('abc').and('contain', 'a')
0 条评论
下一页