Do something as long as element is on page - cypress



  • I'm new to cypress and I just hit this problem I seem unable to solve.

    What I'm trying to do is this: on an eshop page, there's this "Show More Products" button (sorry for the language :)):

    enter image description here

    If I click it, I'll see more products on the page. I need to be able to click this button for as long as I can see it on the page. The reason is there might be many products and clicking the button just once will not get me to the end of the list, so I still might not be able to see all the products.

    The way I see it, this is a simple while loop with a condition.

    And now comes cypress and its asynchronous nature and the page on Conditional Testing I've skimmed through the page, looked for information here and on stackoverflow, tried out some code, but the result is still the same, I have not solved this simple problem. How would you go about this?

    Well, now after I've written all this, there might be one option... I have information about how many pages there're (on the right side in the pic). But it just feels like a horrible solution anyway.



  • Ok so there is a way, but I am not sure if this is "the" way when it comes to Cypress. You can write a recursive function that will call itself when the button is present. I have used a site which has a similar button and got it to work, the code would look something like this:

    function loadMoreProducts() {
        cy.get('body').then((body) => {
            if (body.find('.more_products').length > 0) {
                body.find('.more_products').click()
                cy.wait('@getProducts')
                loadMoreProducts()
            }
        })
    }
    
    it('will load all products', () => {
        cy.server()
        cy.route('products*').as('getProducts')
        loadMoreProducts()
    })
    

    This code is waiting for a route matching a specified url, then calls the loadMoreProducts() function recursively as long as element with '.more_products' class can be found within body of the document. In your case you would have to create a specific route to wait for (which is basically a get request url, captured from 'f12' network tab when you press the 'dalsi produkty' button).


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2