Reputation: 179
I have a table which contains many rows. Only the nth-oldest rows are visible. The newer rows are hidden and one has got to use a scrollbar to move them into sight.
I have written the following Cypress-statement:
cy.get("span.class1.class2").last().click();
It returns the last row, which is visible, when the view becomes shown. Marked red in the screenshot.
But what I like to have is the very last row in the table. Marked blue.
Is that possible with a simple Cypress-statement?
Or do I have to move the scrollbar down first? If so: How can I scroll downwards using Cypress?
Upvotes: 3
Views: 1396
Reputation: 2355
Here is how you could do it with typescript. The main function to look at is scrollToElementTopOrBottom(...)
. This code can handle pages which load items in batches (using a paginated API) instead of all at once. That is, pages in which you can scroll up or down to load elements that are not in the screen or viewport.
You could also convert this logic into javascript code if you don't want to use typescript.
export class MyUtils {
static testMyScrollingCode(): void {
//This DIV is the element which contains all your rows or elements.
cy.get("div").then(($div) => {
this.scrollToElementTopOrBottom($div, "bottom").then(() => {
//Assertions or further actions go here.
});
});
}
static scrollToElementTopOrBottom(element: JQuery<HTMLElement>, position: "top" | "bottom"): Cypress.Chainable<JQuery<HTMLElement>> {
let elementPreviousHeight = 0;
// Recursive function
function scrollToPosition(position: "top" | "bottom"): Cypress.Chainable<JQuery<HTMLElement>> {
return cy
.wrap(element)
.scrollTo(position, { easing: "linear", duration: 500 })
.wait(500)
.then(() => {
const elementCurrentHeight = element[0].scrollHeight;
if (elementCurrentHeight > elementPreviousHeight) {
elementPreviousHeight = elementCurrentHeight;
return scrollToPosition(position);
} else {
return cy.wrap(element);
}
});
}
return scrollToPosition(position);
}
}
Upvotes: 0
Reputation: 11991
Get the parent
class of that table and you could try using scrollTo()
option.
cypress documentation: https://docs.cypress.io/api/commands/scrollto.html#Syntax
Examples:
cy.scrollTo(0, 500) // Scroll the window 500px down
cy.get('.sidebar').scrollTo('bottom') // Scroll 'sidebar' to its bottom
There is another option called .scrollIntoView()
, but I think in your cases the scrollTo() might help.
Upvotes: 4