Search code examples
cypress

Testing multiple queries inside of the same element


Namely, I aim to test multiple queries inside a single element with Cypress.

Here is an example of an element I want to interact with:

<tr id="gZMZs190" class="z-listitem z-listbox-odd z-listitem-selected" title="CAN_BE_REPLACED_BY_2L ->  [] - IQOS ILUMA One Kit Pebbe Grey [G0000592] - Tunisia Product Catalog : Staged" aria-label="Row 10 of 10, CAN_BE_REPLACED_BY_2L ->  [] - IQOS ILUMA One Kit Pebbe Grey [G0000592] - Tunisia Product Catalog : Staged selected" aria-selected="true" role="row" aria-rowindex="10"><td id="gZMZy290" class="z-listcell" tabindex="-1"><div id="gZMZy290-cave" class="z-listcell-content"><div id="gZMZz290" class="ye-default-reference-editor-selected-item-container z-div"><span id="gZMZ_390" class="ye-default-reference-editor-selected-item-label ye-editor-disabled z-label">CAN_BE_REPLACED_BY_2L -&gt;  [] - IQOS ILUMA One Kit Pebbe Grey [G0000592] - Tunisia Product Catalog : Staged</span></div></div></td></tr>

So far I have used this Cypress command, and it works fine:

cy.get('.z-listitem')
.contains("G0000592");

This command successfully checks the product code. Although, our team would also want to check the level at which this product is set (for replacement) which we can see in this part of the element: CAN_BE_REPLACED_BY_2L ->


Solution

  • It's not clear what you mean by "check the level at which this product is set" but if you want to confirm that text, add a .should() after your code.

    cy.get('tr.z-listitem')  // gets the rows
      .contains("G0000592")  // filters according to this text (selecting inner span)
      .should('contain', 'CAN_BE_REPLACED_BY_2L ->')  // assert also has this text
    

    Otherwise, if you refer to the aria-label attribute

    cy.contains('tr', "G0000592")                      // pass on the tr
      .should('contain', 'CAN_BE_REPLACED_BY_2L ->')
      .and('have.attr', 'aria-label')               // look at it's aria-label
      .and('contains', 'CAN_BE_REPLACED_BY_2L ->')  // check attribute's text
    

    The contains() works differently depending on the format. Without any tag (first format) it gives the element lowest in the hierarchy

    <tr>
      <td>
        <div>
          <div>
            <span>  // this one returned
    

    With tr tag specified (second format) it gives the tr

    <tr>     // this one returned
      <td>
        <div>
          <div>
            <span>