Cypress 中是否有一种方法可以模拟网页的分页器功能?
一个示例场景是网页的分页器功能。 因此,此功能或方法将使我能够单击“下一页”或“上一页”图标,直到无法再继续。
我请求信息的代码示例是:
while (cy.get(<locator string>).isClickable()) {
cy.get(<locator string>).click();
//and some other instructions to follow;
}
希望我能够正确地描绘它! ;)
答案 0 :(得分:0)
我不确定这是否有帮助,请告诉我是否有其他方法可以这样做
cy.get('ul[id=myPager] > li').children('a[class^=page_link]').then(function(pages)
{
cy.log(pages.length)
//clicking next until no succeeding pages available to click
for(var x = 1; x < pages.length; x++)
{
cy.get('li').children('a[class=next_link]').click()
if(x === 2)
{
cy.log('No succeeding pages to be clicked')
}
else
{
cy.log('Clicking')
}
}
})
为了自动化前面的页面,只需反转循环:
for(var x=pages.length; x >= 1; x--)
//instructions to follow
答案 1 :(得分:0)
您可以使用 jquery enabled selector 来检查按钮是否已启用,并据此执行其他操作。
cy.get('button').then(($btn) => {
if ($btn.is(":enabled")) {
cy.wrap($btn).click() //Button is enabled
} else {
//Button is disabled
}
})
答案 2 :(得分:0)
while 循环部分可以用递归函数处理,
function clickUntilDisabled(selector, callback, pageNo = 0) {
if (pageNo === 100) {
throw 'Too many clicks' // avoid runaway recursive calls
}
cy.get(selector).then($clickable => {
if ($clickable.prop('disabled')) return; // exit
$clickable.click()
callback(pageNo) // other stuff to do
clickUntilDisabled(selector, callback, ++pageNo) // repeat
})
}
clickUntilDisabled('my-button', (pageNo) => {
cy.get('row').should(...); // testing page here
})
示例应用
<div>
<button onclick="nextpage()">Next Page</button>
<p>Page no: _</p>
<script>
let count = -1
function nextpage() {
count++
console.log('Click handler nextpage', count)
setTimeout(() => { // some async change
const p = document.querySelector('p') // to make sure the loop
p.innerText = `Page no: ${count}` // waits for fetch
}, 2000)
if (count < 3) return
// disable after 3rd click
const button = document.querySelector('button')
button.disabled = true
}
</script>
</div>
测试
function clickUntilDisabled(selector, callback, pageNo = 0) {
if (pageNo === 100) {
throw 'Too many clicks'
}
cy.get(selector).then($clickable => {
if ($clickable.prop('disabled')) return;
$clickable.click()
callback(pageNo)
clickUntilDisabled(selector, callback, ++pageNo)
})
}
clickUntilDisabled('button', (pageNo) => {
console.log('Callback pageNo', pageNo)
cy.get('button')
.then($button => {
const assertion = pageNo < 3 ? 'not.be.disabled' : 'be.disabled';
cy.wrap($button).should(assertion) // passes
})
cy.contains('p', `Page no: ${pageNo}`) // passes
})
日志
Click handler nextpage 0
Callback pageNo 0
Click handler nextpage 1
Callback pageNo 1
Click handler nextpage 2
Callback pageNo 2
Click handler nextpage 3
Callback pageNo 3