opensas
opensas

Reputation: 63405

cypress: css selector to select an anchor by text

I'm starting to play with cypress and I need to select a link like this:

<table cellSpacing="0" cellPadding="0" width="100%" border="0" class="ToolBarBkg">
  <tbody>
    <tr>
      <td class="ContentLeftLinks" align="right" width="98%" height="40" nowrap>
        &nbsp;
        <a href="javascript:FireEvent('Agregar')" style="COLOR: black; font-weight: normal" tabindex="-1">
          <IMG src="/metassc/images/toolbar/AltaOn.gif" align="absmiddle" border=0> Alta
        </a>
        &nbsp;

        <a href="javascript:FireEvent('Eliminar')" style="COLOR: black; font-weight: normal" tabindex="-1">

          <IMG src="/metassc/images/toolbar/BajaOn.gif" align="absmiddle" border=0> Baja
        </a>

Following this page I already tried with these:

cy.contains('a[href~=Agregar]')
cy.contains('a[href*="Agregar"]')
cy.contains('a:contains("^Agregar$") ')
cy.contains('a:contains("^Alta$") ')

But none of them seems to work. Any idea?

Upvotes: 2

Views: 6355

Answers (4)

Dinesh Kumar
Dinesh Kumar

Reputation: 1742

There is this popular library > cypress-testing-library

This makes it really easy to get selectors by text, title, value, alt text etc.

For your issue you can simply use getByText method from this library: cy.getByText('Agregar').click()

Upvotes: 1

soccerway
soccerway

Reputation: 11951

Another way is, you could probably drill down till <a> tag via parent() and find() method in cypress;

cy.get('a:contains("Agregar")').parents('.ToolBarBkg').find('tbody').find('tr').find('td').find('a').contains("Agregar").click();

Upvotes: 0

kuceb
kuceb

Reputation: 18043

cy.contains() can also take two arguments:

cy.contains('a', 'Alta')

This gets the first a element containing the text Alta

Upvotes: 6

opensas
opensas

Reputation: 63405

This seems to work, had to use cy.get instead of contains

cy.get('a[href*="Agregar"]')
  .click()

Upvotes: 0

Related Questions