Darksymphony
Darksymphony

Reputation: 2693

Cypress assert item in table related to it's title

On my page I have multiple tables with this structure:

<div class="box"><h4>Service 1</h4></div>
<div class="container"><ag-grid-table>items in the table</ag-grid-table><div>

<div class="box"><h4>Service 2</h4>
<div class="container"><ag-grid-table>items in the table</ag-grid-table><div>
</div>

<div class="scope-header"><h5>Service 3</h5></div>
<div class="scope-grid"><ag-grid-table>items in the table</ag-grid-table><div>

As you can see, all sections have different structure, and there are even more on the page.

What I want to achieve is to assert that the Service 3 table contains the correct item.

I was thinking about using cy.get('div.scope-header').contains('Service 3') and then using next() or sibling() but the ag-grid-table is neither directly next or sibling.

The only idea I have is to check ag-grid-table:nth(n), this should work, but is there a solution that selects the table according the header title text?

I mean select the table e.g. belonging to Service 3 only.

Upvotes: 1

Views: 753

Answers (4)

Something like this, you can do use Traversal commands.
Adding selectors to next() and sibling() is more robust when page layout changes.

cy.contains('h5', 'Service 3')
  .parent('div.scope-header')
  .next('div.scope-grid')
  .children('ag-grid-table')
  .find('div.ag-row').eq(2)
  ...

Upvotes: 1

TesterDick
TesterDick

Reputation: 10550

You can do something like this with .sibling()

cy.contains('div.scope-header', 'Service 3')
  .sibling('div.scope-grid')                  // move to specified sibling 
  .find('ag-grid-table')                      // within that element
  .should(...)

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18624

From what I understood from your question, You can do something like this:

cy.contains('div.scope-header', 'Service 3')
  .next() //goes to .scope-grid
  .within(() => {
    // scopes search within .scope-grid
    cy.contains('ag-grid-table', 'some text').should('be.visible')
    //OR
    cy.get('ag-grid-table').find('item selector').should('be.visible')
    //OR
    cy.get('ag-grid-table')
      .find('item selector')
      .should('have.text', 'some text')
  })

Upvotes: 1

Fody
Fody

Reputation: 32052

If you want to continue from cy.get('div.scope-header')

cy.contains('div.scope-header', 'Service 3')  // this returns div.scope-header 
                                              // not <h5>Service 3</h5> which 
                                              // cy.get().contains() would do
  .next()                                     // next() moves you to <div class="scope-grid">
  .find('ag-grid-table')                      // table is within that

Upvotes: 2

Related Questions