use*_*624 3 loops if-statement cypress
我有一个包含卡片元素的页面,当用户向下滚动时会加载更多卡片。我正在尝试编写一个测试来向下滚动,直到加载所有卡片元素。
我正在尝试什么:
let stopScroll
let currentCard
let lastCard
let scrollArray = Array.from({length:100},(v,k)=>k+1)
cy.wrap(scrollArray).each((index) => {
if (stopScroll != true) {
cy.get('[data-testid="card"]').last().then(($element) => {
lastCard = $element.text();
})
cy.get('[data-testid="footer"]').scrollIntoView().should('be.visible')
cy.wait(1000)
cy.get('[data-testid="card"]').last().then(($element) => {
currentCard = $element.text();
if (lastCard == currentCard){
stopScroll = true
cy.log(stopScroll)
}
})
.then(() => {
if (stopScroll == true){
return false
}
})
}
})
Run Code Online (Sandbox Code Playgroud)
即使 stopScroll 设置为 true,循环也会继续进行。一切似乎都达到了“.then(()”的程度。我不确定这是否是正确的方法。
您可能可以通过在回调if (stopScroll != true)
内进行检查来做到这一点cy.then()
let stopScroll = false;
cy.wrap(scrollArray).each((index) => {
cy.then(() => {
if (stopScroll != true) {
cy.get('[data-testid="card"]').last().invoke('text').as('card1')
cy.get('[data-testid="footer"]').scrollIntoView().should('be.visible')
cy.wait(1000)
cy.get('[data-testid="card"]').last().invoke('text').as('card2')
cy.get('@card1').then(card1 => {
cy.get('@card2').then(card2 => {
if (card1 !== card2) {
stopScroll = true
}
})
})
}
})
})
Run Code Online (Sandbox Code Playgroud)
原因是stopScroll = true
它只发生在 a 内部.then()
,这意味着它发生在 Cypress 队列上。为了使if()
检查工作,您还需要将其放在 Cypress 队列中 - 即在另一个.then()
.
但 Cypress 可能会对嵌套太多命令感到敏感。如果出现错误,请尝试使用调用自身的函数的替代模式,直到满足条件为止。
function compareCards(counter = 0) {
if (counter > 20) then throw new Error('Too many loops')
cy.get('[data-testid="card"]').last().invoke('text').as('card1')
cy.get('[data-testid="footer"]').scrollIntoView().should('be.visible')
cy.wait(1000)
cy.get('[data-testid="card"]').last().invoke('text').as('card2')
cy.get('@card1').then(card1 => {
cy.get('@card2').then(card2 => {
if (card1 !== card2) {
compareCards(++counter)
}
})
})
}
compareCards()
Run Code Online (Sandbox Code Playgroud)
添加counter
是为了确保它不会无限运行(以防卡片永远不匹配)。您可以增加计数器限制以适合您的测试。