Steve Staple
Steve Staple

Reputation: 3279

Cypress: .each loop to find element that has value

There ought to be a better way of doing this, but I can't find it. There are a number of elements with the same selector on the page. Only the value property differs. Controls are created dynamically, so I can't pin them down any more precisely.

I am searching for an element with a specific value, using Cypress . HTML looks like this:

<input type="button" value="Save" data-cy-component="button-button" class="btn form-control btn-info">

When I find it I want to click it & jump out of the loop.

This is what I have:

 const buttonButton = '[data-cy-component=button-button]';
 cy.get(buttonButton).each(($el, index, $list) => {
  cy.log(`index: ` + index);
  if (index === 5) {
    cy.wrap($el)
      .should('have.value', 'Save')
      // Click Save button.
      .click();
  }
});

This method works, but seems vulnerable. If my Save button is no longer the 5th (or 6th) element, the test will fail. Is there a way I can test it with an IF rather than a SHOULD?

Upvotes: 5

Views: 11198

Answers (1)

Maccurt
Maccurt

Reputation: 13817

I might not understand what you are doing, please correct me in comments if I have this wrong. What I believe you are trying to do is find a element by it's value. I wrote this and it worked. Please correct me If what you are trying to do is different..

<input type="button" value="Save" data-cy-component="button-button" class="btn form-control btn-info">


cy.get('[value="Save"]').should('exist');
cy.get('[value="Save"]').click();
cy.get('input[value="Save"]').should('exist');
cy.get('input[value="Save"]').click();

This also worked

cy.get('[data-cy-component=button-button][value=Save]').should('exist');
cy.get('[data-cy-component=button-button][value=Save]').click();

Per your comment below you said there were 2 on the screen

I created this HTML to test it. Notice one is hidden. I WOULD NEED TO KNOW WHAT IS MAKING YOURS HIDDEN or not visible. Also are they in different divs that perhaps have unique ids?

<input type="button" value="Save" data-cy-component="button-button" class="btn form-control btn-info">
<input style="visibility:hidden" type="button" value="Save" data-cy-component="button-button" class="btn form-control btn-info">


cy.get('[value="Save"][style!="visibility:hidden"]').should('length', 1);
cy.get('[value="Save"][style!="visibility:hidden"]').click();

Upvotes: 2

Related Questions