0

I have this code in my cypress test:

it.only('Checks "Billing" -> invoice section when products are added', () => {
  cy.get('app-product').each(($product, index) => {

    if ($product.find('input.product-name').length > 0) {

      // we need this in order to break the loop and run the test only one time. makes no sence to run the same tests on all products
      cy.wrap($product).find('input.product-name').first().then(($input) => {
        if ($input.val() === 'productName') {
          cy.wrap($product).find('.column-elem.amount').find('.nav-item.actions i-feather[name="more-vertical"].dropdown-toggle').click();
          Elements.getButtonInDropdownMenu(Translations.get('BILLINGS.COPY')).scrollIntoView().click({force: true});
          Permission.isAccessDeniedActionDone();
          Permission.closeAccessDeniedModal();

          // this does not break !!!
          return false;
        }
      });
    }
  });
});

In the html page there can be multiple inputs with the value "productName". In order to be effective I want to run the test only once for one of the inputs. But I can not break the test with "return false;". So my question is: how to run the test only once and/or break the loop in my case?

Arto Avag
  • 97
  • 2
  • 8
  • Does this answer your question? [Why added value en each loop hasn't been stored on next iteration?](https://stackoverflow.com/questions/72384945/why-added-value-en-each-loop-hasnt-been-stored-on-next-iteration) – user16695029 Aug 06 '23 at 20:58

1 Answers1

3

Cypress tests allow queries to be chained, so you can apply the .product-name check and other steps in sequence to give just the DOM section you need.

This means you will start with just one product, no need to iterate! So, simpler is better, you will understand the logic of your test.

cy.get('app-product')
  .find('input.product-name')
  .first()
  .then($input => {
    if ($input.val() === 'productName') {
      cy.wrap($input)
        .parents('app-product')      
        .find('.column-elem.amount')
        ... //etc
    }
  })

Further reading

For an answer to the question about breaking an .each() loop early, read more about it here:
Why added value in each loop hasn't been stored on next iteration

Another very good explanation is given here:
In Cypress loop return true if condition satisfies...

An alternative technique is to apply a .filter() as shown by Emerson here:
How to break out of .each loop with an if/else

Lola Ichingbola
  • 3,035
  • 3
  • 16