Home > Net >  Clicking a button that exists multiple times and is also nested
Clicking a button that exists multiple times and is also nested

Time:12-10

I have a problem that I would like to click a button that exists multiple times on the site and is nested into cards.

I am searching for the card where the name of the pet is Bala, see the attachment below, and I would like to click the Detail labeled button on it.

The furthest I have came with my solution is that I can search for the correct card and just simply click the first of these Detail buttons.

HTML:

<div _ngcontent-eng-1="" >
            <app-pet _ngcontent-eng-1="" _nghost-eng-2="" ><div _ngcontent-eng-2="" >
  <!--template bindings={}--><div _ngcontent-eng-2="" >
    <div _ngcontent-eng-2="" >
      <h4 _ngcontent-eng-2="" >Bala</h4> //Checking this?
      <h6 _ngcontent-eng-2="" >
        <!--template bindings={}--><div _ngcontent-eng-2="" >
          New
        </div>
        <!--template bindings={}--><div _ngcontent-eng-2="" >
          Important
        </div>
        &nbsp;
      </h6>
      <ul _ngcontent-eng-2="" >
        <li _ngcontent-eng-2="" >
          <div _ngcontent-eng-2="" >
            <span _ngcontent-eng-2="">Age: </span>
            <span _ngcontent-eng-2="">20</span>
          </div>
        </li>
        <li _ngcontent-eng-2="" >
          <div _ngcontent-eng-2="" >
            <a _ngcontent-eng-2="" href="/pet/494">
              <img _ngcontent-eng-2="" src="/assets/dog.gif">
            </a>
          </div>
        </li>
        <li _ngcontent-eng-2="" >
          <a _ngcontent-eng-2=""  href="/pet/494">
            Detail
          </a> //CLICK
        </li>
      </ul>
    </div>
  </div>
</div>
</app-pet>
</div>

My code

Then('I click on the Detail button', () => {
  cy.get('div.card').contains('Bala').find('a.btn.btn-primary').click();
});

This is what I have currently but I have already treid some different approaches, like find('a').contains('Detail') or find('a').contains('btn.btn-primary') and some other similar code snippets.

Graphically

This is what the site looks like

Also I have browsed through some similar SO topics but those didn't quite work for me.

CodePudding user response:

You have the right idea to find the card first. This is how you could change your test to do it.

Then('I click on the Detail button', () => {
  cy.contains('div.card', 'Bala').find('a.btn.btn-primary').click();
})

You are specifying the element and the text in one command.

CodePudding user response:

You can use eq if you want to click a particular button:

cy.contains('a', 'Detail').eq(0).click() //Clicks first Detail button
cy.contains('a', 'Detail').eq(1).click() //Clicks second Detail button

Or if you want to click all the buttons one by one you can use each:

cy.contains('a', 'Detail').each(($ele) => {
  cy.wrap($ele).click()
})
  • Related