我有一个基于无限滚动组件的动态加载表格。我可以按如下方式测试加载的项目,但一次只能加载 20 个项目。
如何在不重复代码 100 次的情况下重复直到第 500 项出现?
cy.get('div.infinite-scroll-component')
.children()
.should('have.length', 20)
.last()
.scrollIntoView()
cy.contains('Loading')
.should('be.visible')
<div class="infinite-scroll-component" style="height: auto; overflow: auto;">List:
<div style="height: 30px; border: 1px solid green; margin: 6px; padding: 8px;">Item #0</div>
<div style="height: 30px; border: 1px solid green; margin: 6px; padding: 8px;">Item #1</div>
<div style="height: 30px; border: 1px solid green; margin: 6px; padding: 8px;">Item #2</div>
<div style="height: 30px; border: 1px solid green; margin: 6px; padding: 8px;">Item #3</div>
...
要重复操作直到某个元素出现在页面上,请使用递归函数。
您必须小心,仅在操作完成后才进行下一步。
在您的情况下,“正在加载”指示器已出现,然后等待加载完成(时间可能需要调整)。
const findItem = (item, attempt = 1) => {
if (attempt === 100) throw 'Not found'
return cy.get('div.infinite-scroll-component')
.children()
.then($els => {
const found = [...$els].some(el => el.innerText === item)
if (!found) {
// trigger load with scroll
cy.get('div.infinite-scroll-component')
.children()
.last()
.scrollIntoView()
cy.contains('Loading')
.should('be.visible')
.then(() => {
cy.wait(100) // wait for loading
// OR check the list length
const expectedListLength = (attempt +1) * 20
cy.get('div.infinite-scroll-component').children()
.should('have.length', expectedListLength)
return findItem(item, ++attempt) // next step
})
}
return cy.get('div.infinite-scroll-component')
.children(`:contains(${item})`)
})
}
findItem('div - #100').should('have.length', 1) // just one item
.and('contain.text', 'div - #100') // verify it's text
describe("implemented the cypress scripts for the infinite scroll", () => {
it("test case for the infinite scroll", () => {
cy.visit('https://scrollmagic.io/examples/advanced/infinite_scrolling.html');
cy.get('.box1').should('have.length.greaterThan', 0);
// Define the number of times to scroll
const scrollTimes = 8;
// Define a function to scroll to bottom and assert loader is not visible
const scrollAndWait = () => {
cy.window().scrollTo('bottom',{duration:1000});
cy.get('#loader').should('not.be.visible');
cy.scrollTo('bottom', { duration: 1000 });
};
// Use a loop to scroll multiple times
for (let i = 0; i < scrollTimes; i++) {
scrollAndWait();
cy.wait(1000); // Adjust the wait time as needed
}
// Final assertion to check more items are loaded
cy.get('.box1').should('have.length.greaterThan', 20);
cy.scrollTo('top', {duration:5000})
});
})