.each()
作用
遍历数组数据结构(具有 length 属性的数组或对象)
cy.get('.connectors-each-ul>li')
.each(function($el, index, $list){ //遍历每个li元素
console.log($el, index, $list)
})
.its()
作用
获取对象的属性值
示例代码
cy.get('.connectors-its-ul>li')
// calls the 'length' property returning that value
.its('length')
.should('be.gt', 2)
.invoke()
作用
To invoke a function on a current subject, use the .invoke() command.
对当前对象调用命令
示例代码
cy.get('.connectors-div').should('be.hidden') //断言元素是隐藏状态
// call the jquery method 'show' on the 'div.container' 调用jquery的show方法
.invoke('show')
.should('be.visible') //断言元素是可见状态
.spread()
作用
将数组内容作为单独的参数传回到回调函数
const arr = ['foo', 'bar', 'baz']
cy.wrap(arr).spread(function(foo, bar, baz){
expect(foo).to.eq('foo')
expect(bar).to.eq('bar')
expect(baz).to.eq('baz')
})
.then()
作用
将上一条命令返回的结果注入到下一个命令中
在 Cypress 中,保存一个值或者引用的最好方式是使用闭包
then() 就是 Cypress 对闭包的一个典型应用
then() 返回的是上一个命令的结果,并将其注入到下一个命令中
示例代码1-调用回调函数
cy.get('.connectors-list>li').then(function($lis){
expect($lis).to.have.length(3)
expect($lis.eq(0)).to.contain('Walk the dog')
expect($lis.eq(1)).to.contain('Feed the cat')
expect($lis.eq(2)).to.contain('Write JavaScript')
})
示例代码2-把返回值传递给下一个命令
If the callback function returns a value, it is yielded to the next callback, just like in a Promise callback.
cy.wrap(1)
.then((num) => {
expect(num).to.equal(1)
return 2
})
.then((num) => {
expect(num).to.equal(2)
})
示例代码3
But unlike a Promise, if undefined is returned, then the original value passed into the .then(cb) is yielded to the next callback.
cy.wrap(1)
.then((num) => {
expect(num).to.equal(1)
// note that nothing is returned from this callback
})
.then((num) => {
// this callback receives the original unchanged value 1
expect(num).to.equal(1)
})
示例代码4
If there are Cypress commands in the .then(cb) callback, then the value yielded by the last command will be passed to the next callback.
如果then的回调函数里有cypress命令,上一个命令的返回值会传递给下一个回调函数
cy.wrap(1)
.then((num) => {
expect(num).to.equal(1)
// note how we run a Cypress command
// the result yielded by this Cypress command
// will be passed to the second ".then"
cy.wrap(2)
})
.then((num) => {
// this callback receives the value yielded by "cy.wrap(2)"
expect(num).to.equal(2)
})