Jonas
Jonas

Reputation: 7945

Cypress selecting item in list with .eq(0) also checks conditions in other items

How do I select one item of a list and apply the conditions to only that item?

I have this html:

  <ion-list v-if="mangelzuordnungs.length > 0">
    <ion-item>
      <h2>Item A</h2>
      <button
        data-cy="photo-add-button"
        shape="round"
      >
        <span data-cy="photo-add-button-text"> Hinzufügen </span>
      </button>
    </ion-item>
    <ion-item>
      <h2>Item B</h2>
    </ion-item>
  </ion-list>

And this test:

it('Ensures when Mangelzustand does contains photos, the "Hinzufügen" Button Text does not exist', () => {
    cy.get("ion-item")
      .eq(1)
      .get("[data-cy=photo-add-button")
      .get("[data-cy=photo-add-button-text")
      .should("not.contain", "Hinzufügen");
});

I would expect that the test succeeds because it fails arguing that photo-add-button-text exists and highlights the element of the first list item.

What am I missing?

Upvotes: 1

Views: 867

Answers (2)

user16461847
user16461847

Reputation:

If you use .get() after .eq(1) you are searching from cy.root(), which is the the whole DOM.

Try .find() instead.

cy.get("ion-item")
  .eq(1)
  .find("[data-cy=photo-add-button")
  .find("[data-cy=photo-add-button-text")
  .should("not.contain", "Hinzufügen");

Upvotes: 3

Alapan Das
Alapan Das

Reputation: 18565

Your second item in the list doesn't contain [data-cy="photo-add-button-text] and [data-cy=photo-add-button-text], hence when you are trying to use get(), the test is failing. Instead you can directly assert:

cy.get("ion-item").eq(1).should("not.contain", "Hinzufügen")

Upvotes: 1

Related Questions