Search code examples
javascriptmethodspaginationautomated-testscypress

Cypress pagination handling


I want first to get the #product_list for the full elements list on the current page and then find every element in this list If the element .ajax_block_product.col-xs-12.col-sm-4.col-md-3[data-id-product='22578'] is in the first page then click it, else click on the #pagination_next_bottom button on the bottom of page and search again in other pages to find the element present in #product_list element

I tried with this function but it only finds every page and navigates without clicking on desired element.

// findItem("Printer Brother MFP Laser HL1222WEYJ1");

      // function findItem(value) {
      //   let found = false;
      //   let attempts = 0;
      //   const maxAttempts = 20; // Define a maximum number of attempts
      
      //   function clickNext() {
      //     cy.get("#pagination_next_bottom").click()
      //     cy.wait(5000);
      //   }
      
      //   function findInPage() {
      //     if (found || attempts >= maxAttempts) {
      //       return; // If item found or max attempts reached, exit
      //     }
      
      //     cy.get("#product_list li div.produkti h5").each(itemNameEl => {
      //       const itemText = itemNameEl.text();
      //       console.log(itemText);
      //       if (itemText === value) {
      //         found = true;
      //         cy.get(itemNameEl).should('be.visible').click(); // Click the parent element of the product
      //         return false;
      //       }
      //     });
      
      //     if (!found) {
      //       clickNext(); // Click the "Next" button
      //       attempts++; // Increment attempts
      //       findInPage(); // Continue searching on the next page
      //     }
      //   }
      
      //   findInPage();
      // }

Solution

  • If you're feeling a bit frustrated by the recursion, try it with the cypress-recurse plugin.

    The simplest code would be as follows:

    const itemsSelector = '#product_list li div.produkti'  // leaving off h5
    const nextPageSelector = '#pagination_next_bottom'
    const value = 'Printer Brother MFP Laser HL1222WEYJ1'
    
    recurse(
      () => cy.get(itemsSelector),
      (items) => expect(items).to.contain(value),
      {
        post: () => cy.get(nextPageSelector).click()
      }
    )
    .contains(value)   // filter down to one item
    .click()
    

    Notes:

    • this recurse() returns all items on the page, so filter it with .contains()
    • it works with expect(items).to.contain(value) because your value is quite unique, but if it could partially appear in a different item then you would have to use .each()