V12+的额外柏树查询命令
将此软件包添加为DEV依赖性:
$ npm i -D cypress-map
# or using Yarn
$ yarn add -D cypress-map
在您的规格或支持文件中包含此软件包,以使用所有自定义查询命令
import 'cypress-map'
替代:仅导入您需要的查询命令:
import 'cypress-map/commands/map'
import 'cypress-map/commands/tap'
// and so on, see the /commands folder
const double = ( n ) => n * 2
cy . wrap ( 100 ) . apply ( double ) . should ( 'equal' , 200 )
它的工作方式像cy.then
cy.apply(fn)
函数fn
应该是同步的,纯函数,仅使用主题参数并返回新值函数回调fn
不能使用任何柏树命令cy
。
您可以将其他左参数传递给回调函数。然后,它在调用函数之前将主题作为最后一个参数:
cy . wrap ( 8 ) . apply ( Cypress . _ . subtract , 4 ) . should ( 'equal' , - 4 )
没有争论, cy.applyRight
工作方式与cy.apply
相同。如果您通过参数,则主题加上参数将成为回调的论点。主题在左侧(第一个)位置
cy . wrap ( 8 ) . applyRight ( Cypress . _ . subtract , 4 ) . should ( 'equal' , 4 )
// same as
cy . wrap ( 8 )
. apply ( ( subject ) => Cypress . _ . subtract ( subject , 4 ) )
. should ( 'equal' , 4 )
有时,您需要申请回调,并且您知道第一个参数,只需要将主题放在最后一个位置即可。在这里,您可以将已知参数部分应用于给定的回调。
// the Cypress._.add takes to arguments (a, b)
// we know the first argument a = 5
// so we partially apply it and wait for the subject = b argument
cy . wrap ( 100 ) . partial ( Cypress . _ . add , 5 ) . should ( 'equal' , 105 )
// same as
cy . wrap ( 100 )
. apply ( ( subject ) => Cypress . _ . add ( 5 , subject ) )
. should ( 'equal' , 105 )
如果当前主题是数组或jQuery对象,则可以将带有参数的给定回调应用于第一个项目或元素。当前的主题将是最后一个论点。
// cy.applyToFirst(callback, ...args)
cy . wrap ( Cypress . $ ( '<div>100</div><div>200</div>' ) )
. applyToFirst ( ( base , el ) => parseInt ( el . innerText , base ) , 10 )
. should ( 'equal' , 100 )
如果当前主题是数组或jQuery对象,则可以将带有参数的给定回调应用于第一个项目或元素。当前的主题将是第一个参数。
// cy.applyToFirstRight(callback, ...args)
cy . wrap ( Cypress . $ ( '<div>100</div><div>200</div>' ) )
. applyToFirstRight ( ( el , base ) => parseInt ( el . innerText , base ) , 10 )
. should ( 'equal' , 100 )
我们通常只需要在当前主题中的第一个元素 /项目上调用方法
cy . get ( selector ) . invokeFirst ( 'getBoundingClientRect' )
// compute the vertical center for example
通过通过给定的回调函数运行给定集合中的每个对象。还可以将每个对象映射到其属性。对象可以是数组或jQuery对象。
// map elements by invoking a function
cy . wrap ( [ '10' , '20' , '30' ] ) . map ( Number ) // [10, 20, 30]
// map elements by a property
cy . get ( '.matching' )
. map ( 'innerText' )
. should ( 'deep.equal' , [ 'first' , 'third' , 'fourth' ] )
您甚至可以通过列出回调来映射对象的属性。例如,让我们将age
属性从字符串转换为数字
cy . wrap ( {
age : '42' ,
lucky : true ,
} )
. map ( {
age : Number ,
} )
. should ( 'deep.equal' , {
age : 42 ,
lucky : true ,
} )
您可以避免任何转换以简单地从对象中选择属性列表
const person = {
name : 'Joe' ,
age : 21 ,
occupation : 'student' ,
}
cy . wrap ( person ) . map ( [ 'name' , 'age' ] ) . should ( 'deep.equal' , {
name : 'Joe' ,
age : 21 ,
} )
您可以使用“”提取嵌套路径。在您的财产路径中
cy . wrap ( people )
. map ( 'name.first' )
. should ( 'deep.equal' , [ 'Joe' , 'Anna' ] )
// equivalent to
cy . wrap ( people )
. map ( 'name' )
. map ( 'first' )
. should ( 'deep.equal' , [ 'Joe' , 'Anna' ] )
cy . get ( '#items li' )
. find ( '.price' )
. map ( 'innerText' )
. mapInvoke ( 'replace' , '$' , '' )
. mapInvoke ( 'trim' )
cy . get ( '#items li' )
. find ( '.price' )
. map ( 'innerText' )
. mapInvoke ( 'replace' , '$' , '' )
. map ( parseFloat )
. reduce ( ( max , n ) => ( n > max ? n : max ) )
// yields the highest price
您可以提供初始累加器值
cy . wrap ( [ 1 , 2 , 3 ] )
. reduce ( ( sum , n ) => sum + n , 10 )
. should ( 'equal' , 16 )
请参阅deled.cy.js
cy . get ( '#items li' )
. find ( '.price' )
. map ( 'innerText' )
. tap ( ) // console.log by default
. mapInvoke ( 'replace' , '$' , '' )
. mapInvoke ( 'trim' )
// console.info with extra label
. tap ( console . info , 'trimmed strings' )
注意:如果提供了标签,则使用标签和主题调用回调功能。
一个可用的查询,该查询使用new
关键字和当前主题为参数调用给定的构造函数函数。
cy . wrap ( 'Jan 1, 2019' )
// same as "new Date('Jan 1, 2019')"
. make ( Date )
. invoke ( 'getFullYear' )
. should ( 'equal' , 2019 )
更好的cy.log
:产生值,使用%
和字符串格式符号智能地串制值。
cy . wrap ( 42 )
. print ( ) // "42"
// and yields the value
. should ( 'equal' , 42 )
// pass formatting string
cy . wrap ( 42 ) . print ( 'the answer is %d' ) // "the answer is 42"
cy . wrap ( { name : 'Joe' } ) . print ( 'person %o' ) // 'person {"name":"Joe"}'
// use {0} with dot notation, supported deep properties
// https://github.com/davidchambers/string-format
cy . wrap ( { name : 'Joe' } ) . print ( 'person name {0.name}' ) // "person name Joe"
// print the length of an array
cy . wrap ( arr ) . print ( 'array length {0.length}' ) // "array length ..."
// pass your own function to return formatted string
cy . wrap ( arr ) . print ( ( a ) => `array with ${ a . length } items` )
// if you return a non-string, it will attempt to JSON.stringify it
cy . wrap ( arr ) . print ( ( list ) => list [ 2 ] ) // JSON.stringify(arr[2])
有关更多示例,请参见print.cy.js
在主题中找到一个项目。假设主题是数组或jQuery对象。使用lodash _.find
方法。
// using predicate function
const isThree = n => n === 3
cy . wrap ( [ ... ] ) . findOne ( isThree ) . should ( 'equal' , 3 )
// using partial known properties of an object
cy . wrap ( [ ... ] ) . findOne ( { name : 'Anna' } ) . should ( 'have.property' , 'name' , 'Anna' )
请参阅Find-One.cy.js
cy . get ( '.matching' )
. map ( 'innerText' )
. primo ( )
. invoke ( 'toUpperCase' )
. should ( 'equal' , 'FIRST' )
参见Primo.cy.js
像cy.its
的对象一样工作,但获取jQuery对象的属性,而cy.its
却没有
cy . get ( '#items li.matching' )
. last ( )
. prop ( 'ariaLabel' )
. should ( 'equal' , 'four' )
请参阅Prop.cy.js
通过给定回调功能运行主题内部的单个属性。例如,对类型转换有用,例如,让我们将“年龄”属性转换为一个数字
cy . wrap ( { age : '20' } )
. update ( 'age' , Number )
. should ( 'deep.equal' , { age : 20 } )
从位置k
处返回jQuery对象的DOM元素。从位置k
阵列返回一个项目。对于负索引,从最后计数项目。
cy . get ( '#items li' ) . at ( - 1 ) . its ( 'innerText' ) . should ( 'equal' , 'fifth' )
请参阅at.cy.js
从当前主题返回随机选择的项目或元素
cy . get ( '#items li' ) . sample ( ) . should ( 'have.text' , 'four' )
如果您通过一个正数,则选择多个元素或项目
// yields jQuery object with 3 random items
cy . get ( '#items li' ) . sample ( 3 ) . should ( 'have.length' , 3 )
参见sample.cy.js
从当前主题中产生第二个元素。可能是元素或数组项目。
cy . get ( '#items li' ) . second ( ) . should ( 'have.text' , 'second' )
请参阅second.cy.js
从当前主题中产生第三个元素。可能是元素或数组项目。
cy . get ( '#items li' ) . third ( ) . should ( 'have.text' , 'third' )
请参阅第三
将当前主题保存在Cypress.env
对象中。注意:cypress.env对象是在规格运行之前重置的,但是更改值从测试到测试传递。因此,您可以轻松地将值从第一个测试传递到第二个测试。
it ( 'saves value in this test' , ( ) => {
cy . wrap ( 'hello, world' ) . asEnv ( 'greeting' )
} )
it ( 'saved value is available in this test' , ( ) => {
expect ( Cypress . env ( 'greeting' ) , 'greeting' ) . to . equal ( 'hello, world' )
} )
您是否真的想进行测试彼此取决于彼此?
使用多个选择器查询页面,并以指定顺序返回所找到的元素,无论它们在文档中如何订购。如果找不到任何选择器,请重试。
cy . getInOrder ( 'selector1' , 'selector2' , 'selector3' , ... )
// yields a single jQuery subject with
// elements for selector1
// and selector2,
// and selector3, etc
您也可以使用单个选择器字符串
cy . getInOrder ( [ 'h1' , 'h2' , 'h3' ] )
有时您只想等到元素稳定。例如,如果元素的文本内容没有变化,则可以将元素视为text
稳定的元素。
cy . get ( '#message' ) . stable ( 'text' )
// yields the element
支持类型: text
, value
(对于输入元素), css
和element
(比较元素参考)
您可以控制安静的时期(毫秒),并传递log
和timeout
选项
// stable for 500ms
// without logging
// with maximum retries duration of 6 seconds
cy . get ( '#message' ) . stable ( 'text' , 500 , { log : false , timeout : 6_000 } )
在检查CSS属性稳定时,请提供该属性的名称:
// retries until the CSS animation finishes
// and the background color is red
cy . get ( '#message' )
. stable ( 'css' , 'background-color' , 100 )
// yields the element
. should ( 'have.css' , 'background-color' , 'rgb(255, 0, 0)' )
请参阅stable.cy.js和stable-css.cy.js
实验
重试直到给定选择器从DOM脱离的元件。
cy . contains ( 'Click to re-render' ) . click ( )
cy . detaches ( '#list' )
有时,分离可能会随着动作而发生,而cy.detaches(selector)
为时已晚。如果您知道分离已经发生了,则需要使用存储在Cypress.env
对象中的别名来准备它:
cy . get ( '#name2' ) . asEnv ( 'name' )
cy . contains ( 'Click to remove Joe' ) . click ( )
cy . detaches ( '@name' )
jQuery对象将以name
属性存储在Cypress.env
中。
请参阅distach.cy.js
计算与当前主题对象/数组的差异对象/数组。
cy . wrap ( { name : 'Joe' , age : 20 } )
. difference ( { name : 'Joe' , age : 30 } )
. should ( 'deep.equal' , { age : { actual : 20 , expected : 30 } } )
您可以使用同步谓词函数来验证属性
// confirm the value of the "age" property
// is larger than 15
. difference ( { name : 'Joe' , age : ( n ) => n > 15 } )
报告缺失和额外的属性。参见差异。cy.js
注意:使用have.length
验证数组中的项目数:
// let's check if there are 3 objects in the array
// INSTEAD OF THIS
. difference ( [ Cypress . _ . object , Cypress . _ . object , Cypress . _ . object ] )
// USE AN ASSERTION
. should ( 'have.length' , 3 )
您可以使用预期对象的值 /谓词在数组主题中检查每个项目。
// list of people objects
cy . wrap ( people )
. difference ( {
name : Cypress . _ . isString ,
age : ( age ) => age > 1 && age < 100 ,
} )
. should ( 'be.empty' )
要了解有关cy.table
命令的更多信息,请使用cy.table查询命令阅读博客文章测试HTML表。
从当前主题表中提取所有细胞。产生一个2D的字符串。
cy . get ( 'table' ) . table ( )
您可以将桌子切成薄片以产生一个区域.table(x, y, w, h)
例如,您可以获得2乘2个子区域
cy . get ( 'table' )
. table ( 0 , 2 , 2 , 2 )
. should ( 'deep.equal' , [
[ 'Cary' , '30' ] ,
[ 'Joe' , '28' ] ,
] )
有关更多示例,请参见Spec Table.cy.js。
提示:您可以将cy.table
与cy.map
, cy.mapInvoke
结合在一起,以获取桌子的各个部分。例如,可以提取表的相同2x2部分:
cy . get ( 'table' )
. table ( )
. invoke ( 'slice' , 2 , 4 )
. mapInvoke ( 'slice' , 0 , 2 )
. should ( 'deep.equal' , [
[ 'Cary' , '30' ] ,
[ 'Joe' , '28' ] ,
] )
提示2:要仅获取标题行,请组合.table
表并查询.its
cy . get ( 'table' )
. table ( 0 , 0 , 3 , 1 )
. its ( 0 )
. should ( 'deep.equal' , [ 'Name' , 'Age' , 'Date (YYYY-MM-DD)' ] )
要获得最后一行,您可以做:
cy . get ( 'table' ) . table ( ) . invoke ( 'slice' , - 1 ) . its ( 0 )
要使第一列连接到一个数组中(而不是1x1数组的数组)
cy . get ( 'table' )
. table ( 0 , 1 , 1 ) // skip the heading "Name" cell
// combine 1x1 arrays into one array
. invoke ( 'flatMap' , Cypress . _ . identity )
. should ( 'deep.equal' , [ 'Dave' , 'Cary' , 'Joe' , 'Anna' ] )
查询将特殊的DOM对象转换为普通对象。例如,将DOMStringMap
实例转换为与deep.equal
兼容的普通对象。
cy . get ( 'article' )
. should ( 'have.prop' , 'dataset' )
. toPlainObject ( )
. should ( 'deep.equal' , {
columns : '3' ,
indexNumber : '12314' ,
parent : 'cars' ,
} )
默认情况下,使用JSON Stringify并解析。如果要使用entries
和fromEntries
转换,请添加一个参数:
cy . wrap ( new URLSearchParams ( searchParams ) ) . toPlainObject ( 'entries' )
在柏树v12 cy.invoke
中成为一个查询,这使得使用异步方法的工作真的很笨拙。 cy.invokeOnce
是返回呼叫该方法并产生解决值的旧方式。
cy . wrap ( app )
// app.fetchName is an asynchronous method
// that returns a Promise
. invokeOnce ( 'fetchName' )
. should ( 'equal' , 'My App' )
有关更多示例,请参见Spec Invoke-once.cy.js。
以下是一些示例,可以阐明cy.invoke
, cy.map
和cy.mapInvoke
查询命令之间的不同之处,请参见diff.cy.js
const list = [ 'apples' , 'plums' , 'bananas' ]
// cy.invoke
cy . wrap ( list )
// calls ".sort()" on the list
. invoke ( 'sort' )
. should ( 'deep.equal' , [ 'apples' , 'bananas' , 'plums' ] )
// cy.mapInvoke
cy . wrap ( list )
// calls ".toUpperCase()" on every string in the list
. mapInvoke ( 'toUpperCase' )
. should ( 'deep.equal' , [ 'APPLES' , 'PLUMS' , 'BANANAS' ] )
// cy.map
const reverse = ( s ) => s . split ( '' ) . reverse ( ) . join ( '' )
cy . wrap ( list )
// reverses each string in the list
. map ( reverse )
. should ( 'deep.equal' , [ 'selppa' , 'smulp' , 'sananab' ] )
// grabs the "length" property from each string
. map ( 'length' )
. should ( 'deep.equal' , [ 6 , 5 , 7 ] )
我在此软件包中添加了另一个有用的命令(不是查询!)。它允许您通过同步,异步或CY命令函数通过同步,异步或cy
命令函数在数组中的主题中处理项目。这是因为使用cy.each
进行获取项目的常见解决方案,例如,不起作用:
// fetch the users from a list of ids
// DOES NOT WORK
cy . get ( ids ) . each ( id => cy . request ( '/users/' + id ) ) . then ( users => ... )
// Nope, the yielded "users" result is ... still the "ids" subject
// ✅ CORRECT SOLUTION
cy . get ( ids ) . mapChain ( id => cy . request ( '/users/' + id ) ) . then ( users => ... )
此软件包在文件命令/index.d.ts中包含其自定义命令的打字稿命令定义。从JavaScript规格中使用它:
/// <reference types="cypress-map" />
如果您使用的是打字稿,请在类型列表中包含此模块
{
"compilerOptions" : {
"types" : [ " cypress " , " cypress-map " ]
}
}
源代码在SRC/命令文件夹中。构建命令生成commands
文件夹中的ES5代码(不应将其检查到源代码控制中)。 npm发行版中的package.json
包括commands
以及src/commands/index.d.ts
文件中的类型。
should(callback)
功能。注意:此模块没有filter
方法,因为Cypress API具有查询命令Cy.Filter和Cy.invoke,您可以用来过滤jQuery对象中的元素或数组中的项目。请参阅filter.cy.js规格中的示例。请参阅带有重试的视频过滤器元素和项目。
作者:gleb bahmutov <[email protected]>©2022
许可证:麻省理工学院 - 对代码做任何事情,但是如果它不起作用,请不要怪我。
支持:如果您发现此模块有任何问题,请在GitHub上发送电子邮件 /推文 /打开问题