0

I am having issues with using each loop for lists in cypress.

Website code:

<ul class="list" id="my-list">
  <li>
    <a class="btn-modal"> Text 1</a>
  </li>
  <li>
    <a class="btn-modal">Text 2 </a>
  </li>
  <li>
    <a class="btn-modal">Text 3 </a>
  </li>
</ul>

My test goes like this:

cy.get('[class="list"]')
  .find("li")
  .each((format, i = 0) => {
    const formats = ["Text1", "Text2", "Text3"];
    cy.wrap(format).should("contain", formats[i]);
    i++;
  });

However, it only works for the first item on the list. I did have a workaround though:

cy.get('[class="list"]')
  .find("li")
  .each((format, i = 0) => {
    const formats = ["Text1", "Text1", "Text2", "Text3"];
    cy.wrap(format).should("contain", formats[i]);
    i++;
  });
Fody
  • 23,754
  • 3
  • 20
  • 37
Pb An
  • 25
  • 4

3 Answers3

0

You don't need to initialize or increment the index. It defaults to 0 on the first iteration and will auto increment on each iteration.

See doc here

// move outside of loop
const formats = ['Text1','Text2','Text3']
cy.get('[class="list"]').find('li').each((format, i) => {
    cy.wrap(format).should('contain', formats[i])
    // i++ --> not needed and probably why it doesn't work as you expect
})
Fody
  • 23,754
  • 3
  • 20
  • 37
PeaceAndQuiet
  • 1,692
  • 8
  • 13
0

You should not change the value of i. It will increase automatically for each iteration. Thats probably the issue.

Alex Karamfilov
  • 634
  • 1
  • 6
  • 12
0

You can also invert the loop (but only if order is not important)

const formats = ['Text1','Text2','Text3']
cy.wrap(formats).each(format => {
  cy.contains('[class="list"] li a', format)
})
Fody
  • 23,754
  • 3
  • 20
  • 37